如何使用Nashorn正确评估小脚本?

时间:2017-09-02 21:08:48

标签: javascript java-8 nashorn

我有一个类似于以下的JavaScript脚本

var base = 1
var next = myPackage.MyClass.getResult(base);

以下类在myPackage包中定义

public class MyClass{
  public static getResult(final int base){
    //Inner logic
  return result; //Returns another class defined by me
}

现在,ScriptEngine的eval(String script,Bindings n)方法返回一个脚本的结果,例如示例中的位置

ScriptEngine engine;= new ScriptEngineManager().getEngineByName("nashorn");
bindings = new SimpleBindings();
engine.eval("1 + 1", bindings);
eval调用返回2,我想我可以做类似的事情:

ScriptEngine engine;= new ScriptEngineManager().getEngineByName("nashorn");
bindings = new SimpleBindings();
String baseScript = "var base = 1; var result = myPackage.MyClass.getResult(base);"
String script = baseScript + "result.toString()";
Object result = engine.eval(script, bindings);

但是这个结果总是为null,虽然它正确评估了getResult(base)方法(如果我在里面放置一个断点,我可以检测到调用并且逻辑正确完成)。

为什么结果总是为null,应该如何正确完成?

编辑:完整代码示例:

public class Main {
    public static void main (String[] args) throws java.lang.Exception
    {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        SimpleBindings bindings = new SimpleBindings();
        String baseScript = "var base = 1; var result = Packages.myPackage.MyClass.getResult(base);";
        String script = baseScript + "result.toString()";
        Object result = engine.eval(script, bindings);
        System.out.println(result);
    }
}

package myPackage;
public class MyClass
{
    public static MyClass.ResultClass getResult(final int base) {
        return new MyClass.ResultClass().setString(base);
    }

    public static class ResultClass{
        private String str;

        public MyClass.ResultClass setString(int val){
            if(val < 10) {str = String.valueOf(val);}
            else str = "0";
            return this;
        }
        public String getString(){
            return str;
        }
    }
}

0 个答案:

没有答案