I am passing an object to a scriptEngine using the engine.put() method, and am attempting to retrieve a property of said object using the engine.eval() method. However I can't seem to access them as the object seems to lose its methods when put in the engine, and the get() method I'd normally use in Javascript also seems to fail.
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js");
engine.put("transformContext",transformContext);
engine.put("dataRecordsByName",transformContext.getDataRecordsByName());
//These three all return what I'm expecting - 2x the whole object and then just dataRecordsByName property
System.out.println(engine.get(transformContext));
System.out.println(engine.eval("print(transformContext"));
System.out.println(engine.get(dataRecordsByName));
//These throw errors get() and getDataRecordsByName() seemingly do not exist for transformContext in the engine
System.out.println(engine.eval("print(transformContext.getDataRecordsByName())"));
System.out.println(engine.eval("print(transformContext.get('dataRecordsByName'))"));
}catch(Exception e){
System.err.println("Error evaluating script: "+e.getMessage());
}
I have read that scriptEngine only imports public methods from public classes. In this case though TransformContext is public as are all its methods, so that should be fine?
Any help understanding this or a solution would be appreciated.
After some further research it seems that graal.js does not map properties as you may expect by default, but can do so if you run it in nashorn compatability mode.
System.setProperty("polyglot.js.nashorn-compat", "true");After doing this, you can retrieve the object properties as you normally would in JavaScript:
engine.eval("console.log(transformContext.dataRecordsByName)");Thanks to the guys on this thread: https://github.com/oracle/graaljs/issues/169