如何从Java获取JS对象的属性?

时间:2016-03-02 08:56:56

标签: javascript java rhino nashorn jsr223

我知道我可以使用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

1 个答案:

答案 0 :(得分:2)

您可以将某人投放到JSObject,然后拨打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");