version jdk1.6
很早就听说了这个功能一直没仔细看看,尝试了下 功能不错!
public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
//添加上下文绑定数据
SimpleBindings bindings = new SimpleBindings();
bindings.put("aaa_av", new Double(10000.1));
bindings.put("bbb_av", new Double(20000.2));
ScriptEngine engine = sem.getEngineByExtension("js");
engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
try{
//直接解析
Object res = engine.eval(" res = Math.max(aaa_av , bbb_av) + aaa_av");
System.out.println(res);
//创建脚本
String script = "function getMax() "
+ "{ return Math.max(aaa_av , bbb_av)}";
//执行脚本
engine.eval(script);
Invocable inv = (Invocable) engine;
//执行方法并传递参数
Object obj = inv.invokeFunction("getMax", null);
//打印结果
System.out.println(obj);
}catch(Exception ex){
ex.printStackTrace();
}
}