Question

I am attempting to modify some Javascript code that is embedded in Java to return multiple values to the calling Java code.

Java code (making call to Javascript):

...
Object result = execFunc.call(context, scope, scope, execArgs);
return ScriptRuntime.toString(result);

Javascript code (called by Java):

...
return "string";

I am hoping to return multiple values.

I've tried modifying the Javascript to return a HashMap like so:

...
var res = new java.util.HashMap();
res.put("String", "string");
res.put("Integer", 1);
return res;

But then when I cast on the Java side I get a ClassCastException:

...
HashMap result = (HashMap) execFunc.call(context, scope, scope, execArgs);
return ScriptRuntime.toString(result);

results in:

java.lang.ClassCastException: org.mozilla.javascript.NativeJavaObject cannot be cast to java.util.HashMap

I'm not attached to returning it in a HashMap. The values I want to return are a String and an Integer. Ideally I'm looking to return a tuple or a HashMap but if the only way to get it to work is to return two Strings in an array and then parse out the Integer that would be OK too.

Any guidance for returning multiple values would be greatly appreciated.

Is this the right approach, should I be injecting a Java object that can be populated on the Javascript side instead?

Was it helpful?

Solution

try this

NativeJavaObject njo = (NativeJavaObject) execFunc.call(context, scope, scope, execArgs);
Map map = (Map) njo.unwrap();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top