qinxu

在做项目中有时候需要用到Java调用js文件执行相应的方法

在JDK1.6添加了新的ScriptEngine类,允许用户直接执行js代码。

import org.junit.Test;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * @author ceshi
 * @Title: JunitTestJS
 * @ProjectName ceshi
 * @Description: java 运行js
 * @date 2018/7/1016:35
 */
public class JunitTestJS {

    @Test
    public void test(){
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try{
            engine.eval("function add(a,b){" +
                    "return a+b;" +
                    "}");
            if (engine instanceof Invocable) {
                Invocable in = (Invocable) engine;
                System.out.println(in.invokeFunction("add",1,1));
            }
            }catch(Exception e){
            e.printStackTrace();
        }
    }

}

ps: engine.eval()也可以读入js文件路径来执行js方法

String jsName = "test.js"; 
//读取js
FileReader fileReader = new FileReader(jsName );
//执行指定脚本  
engine.eval(fileReader);   

 

分类:

技术点:

相关文章:

  • 2021-10-20
  • 2019-12-13
  • 2021-12-15
  • 2021-10-19
  • 2021-11-23
  • 2021-12-22
  • 2021-04-09
  • 2021-04-14
猜你喜欢
  • 2021-08-14
  • 2021-11-30
  • 2021-09-30
  • 2021-11-03
  • 2021-07-23
  • 2021-12-15
  • 2021-09-15
相关资源
相似解决方案