3

I know I can use the Invocable class to invoke methods on a 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"

But, how do I get the name attribute of the person? I tried invoker.invokeMethod(person, "name") and I got a NoSuchMethodError.

6
  • I think you will have to "expose" all members you want to share with java part, aka create getters (and optionally setters). Commented Mar 2, 2016 at 9:03
  • You can try to assign the person to variable in JavaScript and use engine.get('person.name') Commented Mar 2, 2016 at 9:05
  • try person.get("name") Commented Mar 2, 2016 at 9:13
  • @awadheshv: person is an Object. It does not have .get. Commented Mar 2, 2016 at 9:23
  • @jcubic - yes that would work but I don't control the JS source in this case. We can invoke methods from Java, why not access members? Commented Mar 2, 2016 at 9:23

1 Answer 1

2

You can cast person to a JSObject and then call person.getMember("name"). Full Java example:

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"));

Or, if the object is stored in the engine global scope like in the following javascript source:

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

you can then call

engine.eval("rick.name");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.