7

我有以下程序,它在 Java (nashorn) 中执行 Javascript。Javascript 代码正在返回一个对象。

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 ";
        }

如何在 Java 中访问结果对象中的对象值?最初,我尝试使用result.toString()来获得结果。好像return [Object Object]

有没有办法,我可以将结果返回给result对象,这样我就可以获得相当于result.value, 和result.count(类似于 Javascript) 的值。

4

2 回答 2

7

如果您的程序的返回值是一个 JavaScript 对象,您应该能够jdk.nashorn.api.scripting.JSObject在 Java 中将其转换为,然后使用它的方法(例如getMember())来查询和操作它。

于 2014-04-15T19:57:00.873 回答
3

您不会JSObject从 JavaScript 函数返回 a 。有效的是

{
  value: value,
  count : count
}

所以你可以使用这个Java代码。

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);
    }
}

输出:

value=10
count=3.0
于 2014-04-16T08:40:52.980 回答