Pass js array to a Java method pointer

qiyi bphanzhu at gmail.com
Tue May 16 18:03:40 UTC 2017


Hi, all, I'am trying to add a function to nashorn engine's bindings, and
these methods I have tried:

public class MyFunction implements Function<Object[], Object> {

    @Override
    public Object apply(Object[] objects) {
        return Arrays.toString(objects);
    }

    public Object f2(Object[] objects) {
        return Arrays.toString(objects);
    }

    public Object f3(Object object) {
        return object;
    }

    public Object f4(Object[] objects) {
        return Arrays.toString(objects);
    }


    public static void main(String[] args) throws ScriptException {
        MyFunction myFunction = new MyFunction();

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine nashorn = manager.getEngineByName("nashorn");
        Bindings bindings = nashorn.getBindings(ScriptContext.ENGINE_SCOPE);

        bindings.put("f1", myFunction);
        bindings.put("f", myFunction);
        bindings.put("f3", (Function<Object, Object>) myFunction::f3);
        bindings.put("f4", (Function<Object[], Object>) myFunction::f4);

        System.out.println(nashorn.eval("f1([1,2])")); // run ok, ret: [1,2]
        System.out.println(nashorn.eval("f.f2([1,2])")); // run ok, ret: [1, 2]
        System.out.println(nashorn.eval("f3(\"f3\")")); // run ok, ret: f3
        System.out.println(nashorn.eval("f4([1,2])")); // run fail,
ClassCastException: ScriptObjectMirror cannot be cast to
[Ljava.lang.Object
    }
}


The problem is the f4 function, this method pointer receive Object[]
parameter and nashorn will throw exception with ClassCastException.

But why nashorn could not infer the parameter type and auto convert
the js array to java array, will it be a bug of nashorn


More information about the nashorn-dev mailing list