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

How to get the attribute of a JS object from Java?

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

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

您可以将 person 转换为 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");