如果我将我的 class 之一的对象绑定到脚本引擎,我如何才能通过脚本引擎将其作为 class 的对象访问?
If I bind an object of one of my classes to a scripting engine, how can I access it as an object of that class from withing the scripting engine?
我希望能够通过 put()
将对象传递到 ScriptEngine
并能够从脚本引擎中访问其属性和方法。
例如
public class MyClass {
String getName() { return "abc"; }
}
MyClass my = new MyClass();
engine.put("abc", my);
我该怎么做?
这是 JavaScript
的完整工作示例。正如我在评论中提到的,您必须确保您的方法是 public
.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptEngineSample {
public static class MyClass {
private String name;
public String getName() { return name; }
public void setName(final String name) { this.name = name; }
}
public static void main(final String[] args) throws ScriptException {
final MyClass my = new MyClass();
my.setName("Input");
final ScriptEngineManager factory = new ScriptEngineManager();
// you could also use 'javascript' here, I'm using 'nashorn' to visualize that I'm using the new Java 8 Engine
final ScriptEngine engine = factory.getEngineByName("nashorn");
engine.put("my", my);
String script = "java.lang.System.out.println(my.getName());";
script += "my.setName('Output');";
engine.eval(script);
System.out.println(my.getName());
}
}
我希望能够通过 put()
将对象传递到 ScriptEngine
并能够从脚本引擎中访问其属性和方法。
例如
public class MyClass {
String getName() { return "abc"; }
}
MyClass my = new MyClass();
engine.put("abc", my);
我该怎么做?
这是 JavaScript
的完整工作示例。正如我在评论中提到的,您必须确保您的方法是 public
.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptEngineSample {
public static class MyClass {
private String name;
public String getName() { return name; }
public void setName(final String name) { this.name = name; }
}
public static void main(final String[] args) throws ScriptException {
final MyClass my = new MyClass();
my.setName("Input");
final ScriptEngineManager factory = new ScriptEngineManager();
// you could also use 'javascript' here, I'm using 'nashorn' to visualize that I'm using the new Java 8 Engine
final ScriptEngine engine = factory.getEngineByName("nashorn");
engine.put("my", my);
String script = "java.lang.System.out.println(my.getName());";
script += "my.setName('Output');";
engine.eval(script);
System.out.println(my.getName());
}
}