Java8 JS Nashorn将数组转换为Java数组

时间:2014-03-18 22:45:51

标签: javascript arrays scala nashorn

如何将JS数组转换为本机数组? 在Rhino中,转换看起来像(Scala代码):

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]

在Nashorn NativeArray缺席,我找不到任何有关转换的文档。

7 个答案:

答案 0 :(得分:16)

从Java(和Scala),您还可以在convert类上调用jdk.nashorn.api.scripting.ScriptUtils方法。例如。来自Java:

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

我的Scala不太流利,但我相信相当于:

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

答案 1 :(得分:7)

给定一个JavaScript数组,您可以使用oracle nashorn engine中的Java.to()方法将其转换为Java数组,该方法在jdk 8中可用

实施例

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

答案 2 :(得分:6)

我找到了适用于Rhino和Nashorn的解决方案。

第一个问题,脚本编写者不得处理Java Objects! 这导致了一个只使用Java的解决方案。

其次它必须适用于Java 8和以前的版本!

    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提供数组作为类sun.org.mozilla.javascript.internal.NativeArray实现java.util.List接口,易于处理

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将JavaScript数组作为jdk.nashorn.api.scripting.ScriptObjectMirror返回,遗憾的是它没有实现List接口。
我用反射解决了这个问题,我想知道为什么甲骨文做了这么大的改变。

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

答案 3 :(得分:2)

解决方案是Java.to函数来进行转换:

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

答案 4 :(得分:1)

如果有数组数组,我们必须递归处理:

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) {}
}

}

答案 5 :(得分:1)

对于多维数组:

您可以使用以下代码获取具有动态维度的数组,具体取决于您要转换的对象。下面有一个用法示例。

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;
}

现在,使用如下方法:

ScriptObjectMirror som = (ScriptObjectMirror) YOUR_NASHORN_ENGINE.eval("['this', ['tricky', ['method', ['works']], 'perfectly'], ':)']");
// create multi-dimensional array
Object[] obj = toArray(som);
瞧,瞧,你明白了。下面是如何迭代这些数组的示例:

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

答案 6 :(得分:0)

我成功通过使用Java8 / Scala2.12 / Nashorn中的传统netscape.javascript.JSObject之类的方法来检索java / scala数组。

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
}

使用ScriptUtil()可以检索标量值,例如String,但它似乎会导致数组ClassCastException