I've encountered an issue in my script where I am able to call methods using invokeMethod()
in Java, but I'm struggling to access the content of object fields. Below is the JavaScript code snippet:
var Test = {
TestVar: "SomeTest",
TestFunc: function() {
print("Hello");
}
};
In the following Java Class:
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptTest {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
engine.eval("var Test = { TestVar: \"SomeTest\", TestFunc: function() { print(\"Hello\");}};");
} catch (ScriptException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println(engine.get("Test"));
System.out.println(engine.get("Test.TestVar"));
System.out.println(engine.get("Test[TestVar]"));
System.out.println(engine.get("Test[\"TestVar\"]"));
Invocable inv = (Invocable) engine;
try {
inv.invokeMethod(engine.get("Test"), "TestFunc");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
The output obtained from this is:
[object Object]
null
null
null
Hello
My question is whether there is a direct way to access the TestVar
variable?