Pass js array to a Java method pointer
Jim Laskey (Oracle)
james.laskey at oracle.com
Tue May 16 18:27:37 UTC 2017
It could have inferred that you meant to pass in a single element object array. Nashorn needs a bit more to determine that you wanted to convert to an java object array.
System.out.println(nashorn.eval("var ObjectArray = Java.type('java.lang.Object[]'); f4(Java.to([1,2], ObjectArray))"));
or more simply
System.out.println(nashorn.eval("f4(Java.to([1,2]))"));
Generally, Nashorn only automatically converts primitive types.
— Jim
> On May 16, 2017, at 3:03 PM, qiyi <bphanzhu at gmail.com> wrote:
>
> 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