直接在Java类中设置变量似乎不起作用。为什么不?什么是正确的语法?变量在哪里?
以下打印出2和1.因此f.x=2;
从未发生过根据f
的Foo
对象。
@Test
public void testJS2Java() throws IOException, ScriptException, Exception {
ScriptEngineManager factory = new ScriptEngineManager();// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
class Foo {
int x = 1;
}
Foo f = new Foo();
engine.put("f", f);
System.out.println(engine.eval("f.x=2;"));
System.out.println(f.x);
}
f.x=2;
执行没有错误,但x
设置?
您的测试有三个问题:
演示从Nashorn访问静态Java字段的工作示例:
import javax.script.*;
public class Main {
public static int x = 10;
public static void main(String[] args) throws Exception {
ScriptEngine e = new ScriptEngineManager().
getEngineByName("JavaScript");
// access type object for Java class "Main" using Java.type
e.eval("var M = Java.type('Main');");
// access public static field 'x' of Main class
e.eval("print(M.x)");
// assign to public static field 'x' of Main class
e.eval("M.x += 10;");
// change is seen from Java
System.out.println(Main.x);
}
}