我正在实现我自己的脚本语言作为副项目,并且语言变量由$ [变量名]访问.但是,当我使用String.replace()用myvar的值(例如'My variable')替换(例如)$ myvar时,使用以下代码:
public static void main(String[] args) { System.out.println(replaceVars("$myvar")); } public static String replaceVars(String source) { String[][] varNames = new String[][]{new String[]{"myvar", "This is a variable"}, new String[]{"anothervar", "This is another variable"}, new String[]{"yetanothervar", "This is yet another variable"}}; String result = source; for(String[] s : varNames) result = result.replace("$" + s[0], s[1]); return result; }
输出:$ myvar
到底是怎么回事?
(原始)给定代码不编译:
Main.java:7: non-static method replaceVars(java.lang.String) cannot be referenced from a static context System.out.println(replaceVars("$myvar")); ^
......除非replaceVars
宣布static
.然后它按预期工作.