How to unbox values returned by javascript (nashorn) in Java object? -
i have following program, executes javascript in java (nashorn) . javascript code returning object.
public object execute(){ scriptenginemanager sem = new scriptenginemanager(); scriptengine e = sem.getenginebyname("nashorn"); invocable invocable = (invocable)e; scriptenginefactory f = e.getfactory(); object result; try { string statement = "function fetch(value, count) { count++ ; return {'value': value,'count' : count} }; } ; "; compiledscript cs = ((compilable)e).compile(statement); cs.eval(); result = invocable.invokefunction("fetch", 10,2); } catch (exception se ) { string version = system.getproperty("java.version"); system.out.println(version); result = "script exception "; } how access object values in result object in java? initially, tried using result.tostring() results. seems return [object object]
is there way, return results result object such values equivalent result.value , , result.count (similar javascript) .
you don't return jsobject javascript function. valid be
{ value: value, count : count } so use java code.
package de.lhorn.so; import javax.script.compilable; import javax.script.compiledscript; import javax.script.invocable; import javax.script.scriptengine; import javax.script.scriptenginemanager; import javax.script.scriptexception; import jdk.nashorn.api.scripting.jsobject; public class soplayground { public static void main(string[] args) throws exception { soplayground sop = new soplayground(); jsobject jso = sop.execute(); system.out.println("value=" + jso.getmember("value")); system.out.println("count=" + jso.getmember("count")); } public jsobject execute() throws scriptexception, nosuchmethodexception { final scriptengine engine = new scriptenginemanager().getenginebyname("nashorn"); final compilable compilable = (compilable) engine; final invocable invocable = (invocable) engine; final string statement = "function fetch(value, count) { count++ ; return {value: value, count : count} };"; final compiledscript compiled = compilable.compile(statement); compiled.eval(); return (jsobject) invocable.invokefunction("fetch", 10, 2); } } output:
value=10 count=3.0
Comments
Post a Comment