Switching from Rhino to Nashorn

前端 未结 7 947
死守一世寂寞
死守一世寂寞 2020-12-13 13:46

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java

7条回答
  •  鱼传尺愫
    2020-12-13 14:17

    Nashorn can not access an inner class when that inner class is declared private, which Rhino was able to do:

    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    public class Test {
       public static void main(String[] args) {
         Test test = new Test();
         test.run();
       }
    
       public void run() {
          ScriptEngineManager factory = new ScriptEngineManager();
          ScriptEngine engine = factory.getEngineByName("JavaScript");
    
          Inner inner = new Inner();
          engine.put("inner", inner);
    
          try {
             engine.eval("function run(inner){inner.foo(\"test\");} run(inner);");
          } catch (ScriptException e) {
             e.printStackTrace();
          }
       }
    
       private class Inner {
          public void foo(String msg) {
             System.out.println(msg);
          }
       }
    }
    

    Under Java8 this code throws following exception:

    javax.script.ScriptException: TypeError: kz.test.Test$Inner@117cd4b has no such function "foo" in  at line number 1
        at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
    

提交回复
热议问题