1700439590
1700439591
public static void main(String[]args)throws Exception{
1700439592
1700439593
//获得一个JavaScript的执行引擎
1700439594
1700439595
ScriptEngine engine=new ScriptEngineManager().getEngineByName(“javascript”);
1700439596
1700439597
//建立上下文变量
1700439598
1700439599
Bindings bind=engine.createBindings();
1700439600
1700439601
bind.put(“factor”,1);
1700439602
1700439603
//绑定上下文,作用域是当前引擎范围
1700439604
1700439605
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
1700439606
1700439607
Scanner input=new Scanner(System.in);
1700439608
1700439609
while(input.hasNextInt()){
1700439610
1700439611
int first=input.nextInt();
1700439612
1700439613
int sec=input.nextInt();
1700439614
1700439615
System.out.println(“输入参数是:”+first+”,”+sec);
1700439616
1700439617
//执行js代码
1700439618
1700439619
engine.eval(new FileReader(“c:/model.js”));
1700439620
1700439621
//是否可调用方法
1700439622
1700439623
if(engine instanceof Invocable){
1700439624
1700439625
Invocable in=(Invocable)engine;
1700439626
1700439627
//执行js中的函数
1700439628
1700439629
Double result=(Double)in.invokeFunction(“formula”,frst, sec);
1700439630
1700439631
System.out.println(“运算结果:”+result.intValue());
1700439632
1700439633
}
1700439634
1700439635
}
1700439636
1700439637
}
1700439638
1700439639
上段代码使用Scanner类接受键盘输入的两个数字,然后调用JavaScript脚本的formula函数计算其结果,注意,除非输入了一个非int数字,否则当前JVM会一直运行,这也是模拟生产系统的在线变更状况。运行结果如下:
[
上一页 ]
[ :1.70043959e+09 ]
[
下一页 ]