Java8 JS Nashorn convert array to Java array

纵饮孤独 提交于 2019-11-30 01:14:00

问题


How can I convert JS array to native array ? In Rhino conversion looked like (Scala code):

val eng = (new javax.script.ScriptEngineManager).getEngineByName("JavaScript")
val obj = eng.eval("[1,2,3,4]")
val arr = obj.asInstanceOf[sun.org.mozilla.javascript.internal.NativeArray]

In Nashorn NativeArray absent, and I can't find any documentation on conversion.


回答1:


From Java (and Scala), you can also invoke convert method on jdk.nashorn.api.scripting.ScriptUtils class. E.g. from Java:

import jdk.nashorn.api.scripting.ScriptUtils;
...
int[] iarr = (int[])ScriptUtils.convert(arr, int[].class)

my Scala is not too fluent, but I believe the equivalent is:

val iarr = ScriptUtils.convert(arr, Array[Int]).asInstanceOf(Array[Int])



回答2:


Given a JavaScript array, you can convert it to a Java array using the Java.to() method in oracle nashorn engine which is available in jdk 8

Example

var data = [1,2,3,4,5,6];
var JavaArray = Java.to(data,"int[]");
print(JavaArray[0]+JavaArray[1]+JavaArray[2]);



回答3:


I found a solution that works for Rhino and Nashorn.

First problem, the script writer must not deal with Java Objects!
That leads to a solution, that only uses Java.

Second it must work with Java 8 and previous versions!

    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("JavaScript");
    try {
        Object result = convert(engine.eval("(function() {return ['a', 'b'];})()"));
        log.debug("Result: {}", result);
        result = convert(engine.eval("(function() {return [3, 7.75];})()"));
        log.debug("Result: {}", result);
        result = convert(engine.eval("(function() {return 'Test';})()"));
        log.debug("Result: {}", result);
        result = convert(engine.eval("(function() {return 7.75;})()"));
        log.debug("Result: {}", result);
        result = convert(engine.eval("(function() {return false;})()"));
        log.debug("Result: {}", result);
    } catch (final ScriptException e) {
        e.printStackTrace();
    }

private static Object convert(final Object obj) {
    log.debug("JAVASCRIPT OBJECT: {}", obj.getClass());
    if (obj instanceof Bindings) {
        try {
            final Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
            log.debug("Nashorn detected");
            if (cls.isAssignableFrom(obj.getClass())) {
                final Method isArray = cls.getMethod("isArray");
                final Object result = isArray.invoke(obj);
                if (result != null && result.equals(true)) {
                    final Method values = cls.getMethod("values");
                    final Object vals = values.invoke(obj);
                    if (vals instanceof Collection<?>) {
                        final Collection<?> coll = (Collection<?>) vals;
                        return coll.toArray(new Object[0]);
                    }
                }
            }
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {}
    }
    if (obj instanceof List<?>) {
        final List<?> list = (List<?>) obj;
        return list.toArray(new Object[0]);
    }
    return obj;
}

Rhino delivers arrays as class sun.org.mozilla.javascript.internal.NativeArray that implement the java.util.List interface, that are easy to handle

13:48:42.400 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class sun.org.mozilla.javascript.internal.NativeArray
13:48:42.405 [main] DEBUG de.test.Tester - Result: [a, b]
13:48:42.407 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class sun.org.mozilla.javascript.internal.NativeArray
13:48:42.407 [main] DEBUG de.test.Tester - Result: [3.0, 7.75]
13:48:42.410 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.String
13:48:42.410 [main] DEBUG de.test.Tester - Result: Test
13:48:42.412 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.Double
13:48:42.412 [main] DEBUG de.test.Tester - Result: 7.75
13:48:42.414 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.Boolean
13:48:42.415 [main] DEBUG de.test.Tester - Result: false

Nashorn returns a JavaScript array as jdk.nashorn.api.scripting.ScriptObjectMirror that unfortunately doesn't implement the List interface.
I solved it using reflection and I'm wondering why Oracle has made this big change.

13:51:02.488 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class jdk.nashorn.api.scripting.ScriptObjectMirror
13:51:02.495 [main] DEBUG de.test.Tester - Nashorn detected
13:51:02.497 [main] DEBUG de.test.Tester - Result: [a, b]
13:51:02.503 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class jdk.nashorn.api.scripting.ScriptObjectMirror
13:51:02.503 [main] DEBUG de.test.Tester - Nashorn detected
13:51:02.503 [main] DEBUG de.test.Tester - Result: [3.0, 7.75]
13:51:02.509 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.String
13:51:02.509 [main] DEBUG de.test.Tester - Result: Test
13:51:02.513 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.Double
13:51:02.513 [main] DEBUG de.test.Tester - Result: 7.75
13:51:02.520 [main] DEBUG de.test.Tester - JAVASCRIPT OBJECT: class java.lang.Boolean
13:51:02.520 [main] DEBUG de.test.Tester - Result: false



回答4:


The solution is Java.to function to do conversion:

engine.eval("Java.to(" + script + ",'byte[]')").asInstanceOf[Array[Byte]]
engine.eval("Java.to(" + name + ",'java.lang.String[]')").asInstanceOf[Array[String]]



回答5:


In case there is array of arrays, we have to process recursivelly:

public class Nashorn {

public static List<String> fromScript(final Object obj){
    List<String> returnList = new ArrayList<>();

    if(obj==null){
        returnList.add("");
        return returnList;
    }

    if (obj instanceof Bindings) {
        flatArray(returnList, obj);
        return returnList;
    }

    if (obj instanceof List<?>) {
        final List<?> list = (List<?>) obj;
        returnList.addAll(list.stream().map(String::valueOf).collect(Collectors.toList()));
        return returnList;
    }

    if(obj.getClass().isArray()){
        Object[] array = (Object[])obj;
        for (Object anArray : array) {
            returnList.add(String.valueOf(anArray));
        }
        return returnList;
    }

    returnList.add(String.valueOf(obj));
    return returnList;
}

//if we have multiple levels of array, flat the structure
private static void flatArray(List<String> returnList, Object partialArray){
    try {
        final Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
        if (cls.isAssignableFrom(partialArray.getClass())) {
            final Method isArray = cls.getMethod("isArray");
            final Object result = isArray.invoke(partialArray);
            if (result != null && result.equals(true)) {
                final Method values = cls.getMethod("values");
                final Object vals = values.invoke(partialArray);
                if (vals instanceof Collection<?>) {
                    final Collection<?> coll = (Collection<?>) vals;
                    for(Object el : coll) {
                        if (cls.isAssignableFrom(el.getClass())) {
                            flatArray(returnList, el);
                        }
                        else{
                            returnList.add(String.valueOf(el));
                        }
                    }
                }
            }
        }
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException
            | IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) {}
}

}




回答6:


For multidimensional arrays:

You can use this code below to get an array with a dynamic dimension, depending on the object you want to convert. There is a usage example below.

public static Object[] toArray(ScriptObjectMirror scriptObjectMirror)
{
    if (!scriptObjectMirror.isArray())
    {
        throw new IllegalArgumentException("ScriptObjectMirror is no array");
    }

    if (scriptObjectMirror.isEmpty())
    {
        return new Object[0];
    }

    Object[] array = new Object[scriptObjectMirror.size()];

    int i = 0;

    for (Map.Entry<String, Object> entry : scriptObjectMirror.entrySet())
    {
        Object result = entry.getValue();

        System.err.println(result.getClass());

        if (result instanceof ScriptObjectMirror && scriptObjectMirror.isArray())
        {
            array[i] = toArray((ScriptObjectMirror) result);
        }
        else
        {
            array[i] = result;
        }

        i++;
    }

    return array;
}

Now, use the method like this:

ScriptObjectMirror som = (ScriptObjectMirror) YOUR_NASHORN_ENGINE.eval("['this', ['tricky', ['method', ['works']], 'perfectly'], ':)']");
// create multi-dimensional array
Object[] obj = toArray(som);

And voila, you got it. Below is an example on how to iterate over such arrays:

public static void print(Object o)
{
    if (o instanceof Object[])
    {
        for (Object ob : (Object[]) o)
        {
            print(ob);
        }
    }
    else
    {
        System.out.println(o);
    }
}



回答7:


I success to retrieve java/scala array by using method like traditional netscape.javascript.JSObject in Java8/Scala2.12/Nashorn.

val arr = engine.eval(script) match {
  case obj:ScriptObjectMirror =>
    if(obj.isArray){
      for(i <- 0 until obj.size()) yield obj.getSlot(i)
    } else Seq.empty
  case unexpected => Seq.empty
}

Using ScriptUtil() may retrieve scalar value such as String, but it seems to cause ClassCastException for Array.



来源:https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!