看书的时候看到如下代码。再此处记录下来:
js代码如下:
function formula(var1,var2){
return var1+var2-factor;
}
java代码如下:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class AboutJavaScript {
public static void main(String[] args) throws Exception {
ScriptEngine engine=new ScriptEngineManager().getEngineByName("javascript");
Bindings bind = engine.createBindings();
bind.put("factor", 1);
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
Scanner input=new Scanner(System.in);
while (input.hasNextInt()) {
int first= input.nextInt();
int sec=input.nextInt();
System.out.println("输入参数是:"+first+","+sec);
engine.eval(new FileReader("F:/model.js"));
if(engine instanceof Invocable){
Invocable in =(Invocable) engine;
Double result=(Double) in.invokeFunction("formula", first,sec);
System.out.println("运行结果:"+result.intValue());
}
}
}
}
选自:编写高质量代码 改善Java程序的151个建议