• Java6 脚本引擎(用Java调用JS脚本)调用js


    Java6 脚本引擎(用Java调用JS脚本)调用js


     import java.io.FileNotFoundException;
     import java.io.FileReader;
     import javax.script.Invocable;
     import javax.script.ScriptEngine;
     import javax.script.ScriptEngineManager;
     import javax.script.ScriptException;
     
     public class JavaScriptEngineTest {
         public static void main(String[] args) {
             try {
                 JavaScriptEngineTest test = new JavaScriptEngineTest();
                 test.testAdd(5, 6);
             } catch (Exception se) {
                 se.printStackTrace();
             }
         }
     
         public String getPath() {
             return this.getClass().getResource("/").getPath();
         }
     
     
         public void testAdd(int a, int b) {
             ScriptEngineManager sem = new ScriptEngineManager();
             ScriptEngine jsEngine = sem.getEngineByName("js");
             try {
                 jsEngine.eval(new FileReader(getPath() + "JavaScriptEngineTest.js"));
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             } catch (ScriptException e) {
                 e.printStackTrace();
             }
             Invocable invocableEngine = (Invocable) jsEngine;
             try {
                 Object ret = invocableEngine.invokeFunction("add", a, b);
                 System.out.println(ret);
             } catch (ScriptException e) {
                 e.printStackTrace();
             } catch (NoSuchMethodException e) {
                 e.printStackTrace();
             }
         }
     
        
     }


    JavaScriptEngineTest.js,放在同一目录:


     function add(a,b) {
       return a+b;
     }
    输出:
    11.0

  • 相关阅读:
    链表习题(2)-一个集合用带头结点的单链表L表示,编写算法删除其值最大的结点。
    ubuntu14安装
    poi多sheet练习
    vmware虚拟机网络模式-仅主机模式
    vmware虚拟机网络模式-NAT模式
    vmware虚拟机网络模式-桥接模式
    IntelliJ IDEA 创建maven
    IntelliJ IDEA
    冒泡
    Java泛型 通配符? extends与super
  • 原文地址:https://www.cnblogs.com/vipbooks/p/5905862.html
Copyright © 2020-2023  润新知