Is it worked Nashorn JS object to java.util.Map?

天涯浪子 提交于 2019-12-23 09:34:41

问题


I have java method

void someMethod(String str, Map map) {
    ...
}

From JS call this method

var map = new Object()
map.key1 = "val1"
...someMethod(str, map)

Exception:

java.lang.NoSuchMethodException: None of the fixed arity signatures
[(java.lang.String, java.util.Map)] of method org.prjctor.shell.Bash.eval
match the argument types [java.lang.String, jdk.nashorn.internal.scripts.JO]

But in Nashorn docs "Mapping of Data Types Between Java and JavaScript" said "Every JavaScript object is also a java.util.Map so APIs receiving maps will receive them directly".

What am I doing wrong?


回答1:


Agree with the previous answers that you cannot do this as the docs have implied. However you could create and pass a map as follows

..
var HashMap = Java.type('java.util.HashMap');
var map = new HashMap();
map.put('1', 'val1');
...someMethod(str, map)



回答2:


The doc says ""Every JavaScript object implements the java.util.Map interface". But this sample test program shows thats not the case.

public final class NashornTestMap {
    public static void main(String args[]) throws Exception{
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine nashorn = factory.getEngineByName("nashorn");
        nashorn.eval(""
                +"load(\"nashorn:mozilla_compat.js\");"
                + "importClass(Packages.NashornTestMap);"
                + "var map={};"
                + "map[\"Key\"]=String(\"Val\"); "
                + "var test = new NashornTestMap();"
                + "test.test(map);"
                + "");
    }

    public void test(Map<String, String> obj){
        System.out.println(obj);
    }       
}

The above code give exception "Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.scripts.JO4 to java.util.Map". This link confirms this.

However you can use Map inside your script and call the java objects directly, like this.

public final class NashornTestMap {
    public static void main(String args[]) throws Exception{
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine nashorn = factory.getEngineByName("nashorn");
        nashorn.eval(""
                +"load(\"nashorn:mozilla_compat.js\");"
                + "importClass(Packages.NashornTestMap);"
                + "var HashMap = Java.type(\"java.util.HashMap\");"             
                + "var map = new HashMap();"
                + "map.put(0, \"value1\");"
                + "var test = new NashornTestMap();"
                + "test.test(map);"
                + "");
    }

    public void test(Map<String, String> obj){
        System.out.println(obj);
    }       

}

Returns "{0=value1}"



来源:https://stackoverflow.com/questions/20512621/is-it-worked-nashorn-js-object-to-java-util-map

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