Rhino:如何将Java对象传递给脚本,其中可以引用为“this”。
我是JSR-223 Java Scripting的新手,实际上我正在从 MVEL 到标准 Mozilla Rhino JS 。我已阅读所有文档,但卡住了。我试图通过绑定从脚本中引用一些Java对象,就像在教程中一样:
I am new to JSR-223 Java Scripting, actually I'm switching from MVEL to standard Mozilla Rhino JS. I have read all documentation, but get stuck. I have tried to reference some Java objects from script by bindings just like in tutorial:
// my object
public class MyBean {
public String getStringValue() { return "abc" };
}
// initialization
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// add bindings
engine.put("bean", new MyBean());
// evaluate script, output is "abc"
engine.eval("print(bean.stringValue)");
Java对象从脚本引用为属性 bean
。到现在为止还挺好。
Java object is referenced from script as property bean
. So far so good.
但是我想在脚本中引用我的对象这个
,我想要使用它的属性和方法而没有任何前缀或明确地使用前缀此
。就像这样:
But I want to reference my object in script as this
, I want to use its properties and methods without any prefix or explicitely with prefix this
. Just like this:
// add bindings
engine.put(....., new MyBean()); // or whatever ???
// evaluate scripts, all have the same output "abc"
engine.eval("print(stringValue)");
engine.eval("print(this.stringValue)");
我知道JavaScript中的这个
有特殊之处意思是(如在Java中),但在MVEL脚本中可以通过使用自定义 ParserContext
和自定义 PropertyHandler
。
I know that this
in JavaScript has special meaning (as in Java) but in MVEL scripting that could be done by using custom ParserContext
and custom PropertyHandler
.
在Rhino中是否可以这样?
非常感谢。
好吧,在JavaScript中,只考虑这个
在被调用的函数的上下文中设置。因此,我认为您应该能够在ScriptEngine上使用invoke方法(必须将其转换为Invocable):
Well, in JavaScript it really only makes sense to think about this
being set in the context of a function being invoked. Thus I think you should be able to use the "invoke" method on the ScriptEngine (which has to be cast to "Invocable"):
((Invocable) engine).invokeMethod(objectForThis, "yourFunction", arg, arg ...);
现在,objectForThis引用(根据我的经验)通常是先前调用返回的内容toeval()(或invokeMethod我猜);换句话说,它应该是脚本引擎的适当语言中的对象。无论你是否可以在那里传递一个Java对象(并让它成功),我都不确定。
Now the "objectForThis" reference is (in my experience) generally something that was returned from a prior call to "eval()" (or "invokeMethod" I guess); in other words, it's supposed to be an object in the appropriate language for the script engine. Whether you could pass in a Java object there (and have it work out), I don't know for sure.