在JAVA中调用Javascript代码
有些时候,我们在执行JAVA代码的时候,希望能够通过执行其他脚本语言(如js, 修改脚本新逻辑立即生效,不需要重新加载)根据其结果来进行逻辑判断,自java SE 8开始已经集成了Nashorn Javascript引擎作为JDK的一部分。
1.使用nashorn引擎
1.1直接执行脚本
1.1.1查询引擎使用nashorn
public static void main(String[] args) throws Exception {ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine scriptEngine =scriptEngineManager.getEngineByName("nashorn");scriptEngine.eval("print('Hello,World')");
}
1.1.2查询引擎使用Javascript
public static void main(String[] args) throws Exception {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("Javascript");
scriptEngine.eval("print('Hello,World')");
}
1.2 执行脚本指定函数
1.2.1查询引擎使用nashorn
public static void main(String[] args) throws Exception {ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine scriptEngine =scriptEngineManager.getEngineByName("nashorn");scriptEngine.eval("function hello(name){print('Hello,'+ name )}");Invocable inv = (Invocable) scriptEngine;inv.invokeFunction("hello", "Javascript");}
1.2.2查询引擎使用Javascript
public static void main(String[] args) throws Exception {ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");scriptEngine.eval("function hello(param) {\n" +" if(param == '123') {\n" +" return true;\n" +" }\n" +" return false;\n" +"}");Invocable inv = (Invocable) scriptEngine;boolean result = (Boolean) inv.invokeFunction("hello", "12");System.out.println(result);
1.3 获取的都是nashorn引擎
scriptEngineManager.getEngineByName("nashorn");scriptEngineManager.getEngineByName("Javascript");
2. 使用脚本语言的优点
- 脚本语言可以直接运行,不需要编译为字节码,如果修改了逻辑不需要重新启动应用,立刻生效
- 动态类型,创建变量不需要创建及声明类型,可以重复使用变量
参考
https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/about.html#sthref8
https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html#CDEGJDJF