3
我知道我可以使用Invocable類調用一個類的方法:如何從Java獲取JS對象的屬性?
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
。
我想你將不得不「暴露」你想與java部分共享的所有成員,也就是創建getter(和可選的setter)。 – Rafouille
您可以嘗試在JavaScript中將人員分配給變量並使用'engine.get('person.name')' – jcubic
嘗試'person.get(「name」)' – awd