public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
//建立上下文环境
Bindings bind = engine.createBindings();
bind.put("factor", 1);
//绑定上下文,作用域是当前引擎范围
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
//接收参数输入
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt()){
int first = scanner.nextInt();
int second = scanner.nextInt();
System.out.println("接收参数为:"+first+","+second);
//引擎执行脚本
engine.eval(new FileReader("c:/modal.js"));
//判断是否为可执行的
if(engine instanceof Invocable){
Invocable in = (Invocable)engine;
Double result = (Double) in.invokeFunction("formula", first,second);
System.out.println("执行结果为:"+result);
}

}

}

 

 

C盘下modal.js脚本内容如下:

function formula(value1,value2){
  return value1+value2-factor;
}

posted on 2015-02-27 15:57  竹林后生  阅读(495)  评论(0编辑  收藏  举报