Is this possible for use javascript to call a java method?

后端 未结 4 2051
太阳男子
太阳男子 2021-01-02 18:18

The java have a script manager that allow java calling javascript, like this:

import javax.script.*;
public class ExecuteScript {
 public static void main(St         


        
4条回答
  •  长发绾君心
    2021-01-02 18:59

    Here is a tiny example with Java 8 Nashorn that works as a stand-alone script without any packages:

    import javax.script.*;
    import java.util.LinkedList;
    
    public class RunJavaFromJs {
      public static void main(String[] args) throws Exception {
        LinkedList jList = new LinkedList<>();
        jList.add((Integer)42);
    
        ScriptEngine engine = 
          (new ScriptEngineManager())
          .getEngineByName("nashorn");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("jList", jList);
        engine.eval("" + 
          "load('nashorn:mozilla_compat.js');\n" +
          "// call static method\n" + 
          "var i = Packages.RunJavaFromJs.helloWorld(42);\n" + 
          "// perform side effect\n" + 
          "print('Result was: ' + i + '(printed from JS)');\n" + 
          "// call method on `jList` instance passed in bindings \n" +
          "jList.add(12345);\n" +
          "print(jList.toString());"
        );
      }
      public static int helloWorld(int x) {
        System.out.println("Hello, world! (printed from Java in static method)");
        return x * x;
      }
    }
    

    If you just save it in RunJavaFromJs.java, then compile and run using

    javac RunJavaFromJs.java && java RunJavaFromJs
    

    then you obtain:

    Hello, world! (printed from Java in static method)
    Result was: 1764(printed from JS)
    [42, 12345]
    

提交回复
热议问题