[英]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?
I want to be able to pass an object into ScriptEngine
via put()
and be able to access its properties and methods from within the scripting engine. 我希望能够通过
put()
将对象传递给ScriptEngine
,并能够从脚本引擎内部访问其属性和方法。
eg 例如
public class MyClass {
String getName() { return "abc"; }
}
MyClass my = new MyClass();
engine.put("abc", my);
How can I do this? 我怎样才能做到这一点?
Here is a complete working example with JavaScript
. 这是一个使用
JavaScript
的完整示例。 As I mentioned in the comment, you have to make sure that your methods are public
. 正如我在评论中提到的那样,您必须确保您的方法是
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.