Reputation: 3027
I want to provide my own implementation of JSObject as described here: https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions JSObject is within the jdk.nashorn.api package. Unfortunately the classes of the objects you get in the api-methods are not. You get NativeArray and JO4, which are both part of the internal package. My question is, how should I handle such objects? Is it recommended to use the internal functions? Or is it possible to cast those objects to anything in the api-package?
Here is my simple example:
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.AbstractJSObject;
public class JacksonToJSObject extends AbstractJSObject {
final static ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
String script = "var fun = function(obj) {obj.arrayField = [1,2]; obj.objField = {\"field\":\"test\"}};";
engine.eval(script);
((Invocable)engine).invokeFunction("fun", new JacksonToJSObject());
}
@Override
public void setMember(String name, Object value) {
System.out.println(value.getClass().getCanonicalName());
}
}
This is the output
jdk.nashorn.internal.objects.NativeArray
jdk.nashorn.internal.scripts.JO4
Upvotes: 2
Views: 970
Reputation: 4405
I've filed a bug against JDK https://bugs.openjdk.java.net/browse/JDK-8137258 to automatically handle the wrapping. In the meanwhile, please use the workaround suggested by Attila Szegedi.
Upvotes: 2
Reputation: 4595
I think we should wrap these automatically for you. In the meantime, you can pass these internal objects to jdk.nashorn.api.scripting.ScriptUtils.wrap(Object)
yourself to get back a JSObject
. This method is idempotent if you pass it something that's already wrapped, so this solution won't break if we fix the wrapping.
Upvotes: 2