如何在Java对象中取消javascript(nashorn)返回的值?

时间:2014-04-15 16:55:12

标签: java javascript nashorn

我有以下程序,它在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.valueresult.count的值(类似于Javascript)。

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:3)

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

{
  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