Java调用代码:

import jdk.nashorn.api.scripting.*;
....
myCustomHashMap dataStore = new myCustomHashMap();
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("nashorn");
engine.put("dataStore",dataStore);
engine.eval(new java.io.FileReader("test.js"));
((Invocable)engine).invokeFunction("jsTestFunc", "testStr" );

Javascript:
function jsTestFunc (testParam)
  { dataStore.a = [1,2,3];
    dataStore.b = {First:"John",Last:"Doe",age:37}; }

目标:
I need to JSONify the dataStore after the script execution
with no dependence on the script for assistance

dataStore.a -> jdk.nashorn.internal.objects.NativeArray
dataStore.b -> jdk.nashorn.internal.scripts.JO4

对于每个Map值,我都尝试并失败了:
  • 转换为ScriptObject或ScriptObjectMirror
  • 转换到 map 或列表
  • 直接访问JO4/NativeArray方法
  • ScriptUtils.wrap()/ScriptUtils.unwrap()

  • 我尝试覆盖HashMap.put()方法,但似乎仅在显式函数调用上不会将其转换为赋值的ScriptObjectMirror:
    dataStore.x = [1,2,3] ; -> jdk.nashorn.internal.objects.NativeArray
    
    javaHost.javaFunc( [1,2,3] ); -> ScriptObjectMirror
    

    我真的需要使用myCustomHashMap(它的时间戳更改并维护更改列表等),所以我不能从根本上改变这种安排。我该怎么做才能取回这些数据?

    最佳答案

    这是一个错误。



    https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes

    与JDK8u40抢先体验版

    Java的:

    public class MyObject extends HashMap<String, Object> {
        @Override
        public Object put(String key, Object value) {
            System.out.println("Key: " + key + " Value: " + value + " Class: " + value.getClass());
            return super.put(key, value);
        }
    }
    

    JavaScript:
    var MyObject = Java.type("my.app.MyObject");
    var test = new MyObject;
    test.object = {Test : "Object"};
    test.array = [1,2,3];
    

    安慰:
    Key: object Value: [object Object] Class: class jdk.nashorn.api.scripting.ScriptObjectMirror
    Key: array Value: [object Array] Class: class jdk.nashorn.api.scripting.ScriptObjectMirror
    

    关于java - 读取Nashorn JO4和NativeArray,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26392602/

    10-11 01:34