java的脚本编程,在不用重新发版情况下就能修改业务实现,实用性还是挺不错的
现举一小例子
java 类:ScriptJava
public class ScriptJava {
public static void main(String[] args) {
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);
try {
engine.eval(new FileReader("C:/works_eprk/BetterJava151/src/com/java151/b01/model.js"));
if (engine instanceof Invocable) {
Invocable in = (Invocable) engine;
Double result;
try {
result = (Double) in.invokeFunction("formula", first, sec);
System.out.println(result.intValue());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
}
js 文件:model.js
function formula (var1,var2) {
return var1 - var2 * factor;
}
现举一小例子
java 类:ScriptJava
public class ScriptJava {
public static void main(String[] args) {
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);
try {
engine.eval(new FileReader("C:/works_eprk/BetterJava151/src/com/java151/b01/model.js"));
if (engine instanceof Invocable) {
Invocable in = (Invocable) engine;
Double result;
try {
result = (Double) in.invokeFunction("formula", first, sec);
System.out.println(result.intValue());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
}
js 文件:model.js
function formula (var1,var2) {
return var1 - var2 * factor;
}