java中调用js函数的方法

        有时候由于一些不能说的原因,可能会遇到需要在java代码中调用js函数的场景,下面就来说说如何调用吧。

        首先说明一点,java不支持浏览器本身的方法,只支持自定义的js方法,否则会报错

       1. 先建一个js文件,test.js,内容如下:

function add(a,b){
    return a+b;
}

      2. 在java代码中调用js函数

public class Test {
    
    public static void main(String[] args) throws Exception {
        
          ScriptEngineManager manager = new ScriptEngineManager();
          ScriptEngine engine = manager.getEngineByName("js");
          String jsFileName="D:\\test.js";  //js文件所在目录
          FileReader reader = new FileReader(jsFileName);   // 执行指定脚本   
          engine.eval(reader);   
          if(engine instanceof Invocable) {    
          Invocable invoke = (Invocable)engine;    // 调用merge方法,并传入两个参数    
          Double c = (Double)invoke.invokeFunction("add", 1, 2); //调用了js的add方法
          System.out.println(c);          
      }
 
    }
}

        运行结果为:3

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章