I have been using GraalVM to execute Javascript from java. But i have a problem: I don't know how to get fields or invoke methods of a js object from java. This is my code, java:
public static class JavaMethods {
public void printWidthOf(Object size) {
System.out.println("printWidthOf started");
System.out.println("size class is " + size.getClass().getName()); // prints PolyglotMap
Map map = (Map) size; // PolyglotMap implements Map so i tried that
System.out.println("size width is " + map.get("size")); // doesn't work, prints null instaed of 40
}
}
public static void main(String[] args) throws Exception {
GraalJSEngineFactory factory = new GraalJSEngineFactory();
GraalJSScriptEngine engine = factory.getScriptEngine();
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("polyglot.js.allowHostAccess", true);
bindings.put("JavaMethods", new JavaMethods());
engine.eval(new FileReader("MyScript.js"));
engine.invokeFunction("start");
}
javascript:
class Size {
#width;
#height;
constructor(w, h) {
this.#width = w;
this.#height = h;
}
getWidth() {
return this.#width;
}
getHeight() {
return this.#height;
}
}
function start() {
var mySize = new Size(40, 60);
JavaMethods.printWidthOf(mySize);
}
Output:
printWidthOf started
size class is com.oracle.truffle.polyglot.PolyglotMap
size width is null
Then how can i get a field of a PolyglotMap (js object) from java?