Rhino:如何将Java对象传递给脚本,其中可以引用为“this”。 [英] Rhino: How to pass Java object to script, where can be referenced as "this"

查看:192
本文介绍了Rhino:如何将Java对象传递给脚本,其中可以引用为“this”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSR-223 Java Scripting的新手,实际上我正在从 MVEL <切换/ a>到标准 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.

这篇关于Rhino:如何将Java对象传递给脚本,其中可以引用为“this”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆