Search code examples
javajava-8nashorn

How to avoid internal Nashorn classes in implementations of JSObject


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

Solution

  • 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.