问题
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