3

我知道我可以使用Invocable类来调用类上的方法:

import javax.script.{ScriptEngine, ScriptEngineManager, Invocable}

val engine = new ScriptEngineManager().getEngineByExtension("js")

val invoker = engine.asInstanceOf[Invocable]

val person = engine.eval(s"""
  new function () {
    this.name = "Rick";
    this.age = 28;
    this.speak = function () {
      return this.name + "-" + this.age;
    }
  };
""")

invoker.invokeMethod(person, "speak") //returns "Rick-28"

但是,我如何获得name人的属性?我试过 invoker.invokeMethod(person, "name")了,我得到了一个NoSuchMethodError.

4

1 回答 1

2

您可以将 person 转换为 aJSObject然后调用person.getMember("name")。完整的 Java 示例:

ScriptEngine engine = new ScriptEngineManager()
                           .getEngineByExtension("js");

JSObject rick = (JSObject) engine.eval("new function () {\n" +
        "            this.name = \"Rick\";\n" +
        "            this.age = 28;\n" +
        "            this.speak = function () {\n" +
        "                return this.name + \"-\" + this.age;\n" +
        "            }\n" +
        "        };");

System.out.println(rick.getMember("name"));

或者,如果对象存储在引擎全局范围内,如以下 javascript 源代码:

rick = function() {
  this.name= "Rick";
};

然后你可以打电话

engine.eval("rick.name");
于 2016-03-02T09:38:57.307 回答