一:前言
今天领导给安排任务,说看下js引擎,后面要安排相关任务,然后就在网上搜了一些资料随便看看
二:使用
先在目录下定义一个js文件,
function sayHello(name){
return "Hello,"+name;
}
function increment(i){
return i+2;
}
function min(i){
return i+5;
}
然后定义一个与之一一对应的接口类
package com.dingwang.js.engine;
/**
* 类IJsEngine.java的实现描述:TODO 类实现描述
*
* @author dingwang 2016年1月12日 下午2:39:56
*/
public interface IJsEngine {
String sayHello(String name);
int increment(int i);
int min(int j);
}
调用方法
package com.dingwang.js.engine;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
/**
* 类JsEngineClient.java的实现描述:TODO 类实现描述
*
* @author dingwang 2016年1月12日 下午2:42:15
*/
public class JsEngineClient {
public void invokeJsEngine() throws UnsupportedEncodingException, IOException, ScriptException {
Resource resource = new FileSystemResource("E:\\selfworkspace\\Framework\\src\\main\\resources\\jsEngine.js");
InputStreamReader is = null;
is = new InputStreamReader(resource.getInputStream(), "UTF-8");
String str = "";
int tmp = 0;
while ((tmp = is.read()) != -1) {
str += (char) tmp;
}
System.out.println("脚本内容----------str=" + str);
getEngine(str);
}
private void getEngine(String script) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval(script);
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
IJsEngine iEngine = invocable.getInterface(IJsEngine.class);
System.out.println("执行结果-------------" + iEngine.sayHello("dingwang"));
System.out.println("执行结果-------------" + iEngine.increment(2));
}
}
}
当然还有许多其他的方法,具体的可以网上搜搜
三:注意点
接口类里面的方法签名和js里面的方法签名保持一致,不然会报错,不过我试了下,方法名一样但是参数不一样时也不会报错,用这种方法要注意效率问题