How to use the Java interop was: graal-js - passing JS native object to Java - com.oracle.truffle.object.enterprise.b
Jaroslav Tulach
jaroslav.tulach at oracle.com
Tue Jan 9 05:33:35 UTC 2018
Hello Adam,
didn't we already talked about interop in December? I think I suggested you to
take a look at https://github.com/graalvm/graal-js-archetype - I know it may
feel complex to follow, but I would still advice you to look at it, as it
shows how the Truffle/JS/Java interop has been designed to work.
For example https://github.com/graalvm/graal-js-archetype/blob/master/
archetype/src/main/resources/archetype-resources/src/main/java/
Services.java#L131 shows how easy it is to access any JavaScript object in a
type-safe way from Java. You should follow that pattern too.
Once upon a time me and Michael Van De Vanter added a tutorial explaining
these concepts. Currently it can be found at https://oracle.github.io/graal/
truffle/javadoc/com/oracle/truffle/tutorial/embedding/package-summary.html - copy
the content, the URL may not last long. It contains examples of various ways
to pass native JS object to Java and view it as a Map, List, or any other
dedicated interface.
>> Adam McMahon <adam at cs.miami.edu>: 08.01.18 @ 20:53 <<
> Hi,
> Here is the snippet of code I am working on. It passes a native JS object
> to Java. https://gist.github.com/AdamMcM/87bed21323aa5ff90ed020412f16eb02
I've applied the techniques used in the archetype and the tutorial to your
Gist and below is the result. I hope you will now find the Truffle/JS/Java
interop joyful to use!
-jt
package adamtest;
import java.util.Map;
import javax.script.*;
public class AdamTest {
public static void main(String[] args) {
try {
ScriptEngine engine = new
ScriptEngineManager().getEngineByName("graal.js");
// ScriptEngine engine = new
ScriptEngineManager().getEngineByName("nashorn");
if (engine != null) {
StringBuilder sb = new StringBuilder();
sb.append("var Utils = Java.type('adamtest.AdamTest');");
sb.append("var obj = {};");
sb.append("obj.n=100;");
sb.append("print(''+ obj.n);");
sb.append("Utils.passToJava(obj);");
sb.append("Utils.passAsObjWithN(obj);");
sb.append("Utils.passAsMap(obj);");
engine.eval(sb.toString());
} else {
System.out.println("null engine");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void passToJava(Object o) {
System.out.println("class name = " + o.getClass().getName());
}
public interface ObjWithN {
public int n();
}
public static void passAsObjWithN(ObjWithN o) {
System.out.println("class name = " + o.getClass().getName());
System.out.println("obj value = " + o.n());
}
public static void passAsMap(Map<String, Integer> o) {
System.out.println("class name = " + o.getClass().getName());
System.out.println("map " + o);
}
}
More information about the graal-dev
mailing list