最近项目开发中用到了java调用js脚本的需求,在此做一下记录:下面为kotlin代码
val manager = ScriptEngineManager()
val engine = manager.getEngineByName("javascript")
try {
engine.eval("function transform(variable){\n" +
"if(variable == '4'){\n" +
" return true;\n" +
"}else {\n" +
" return false\n" +
" }\n" +
"}")
if (engine is Invocable) {
val `in` = engine as Invocable
if (`in`.invokeFunction("transform", "20") as Boolean){
System.out.println("有")
}else{
System.out.println("没有")
}
}
} catch (e: Exception) {
e.printStackTrace()
}
java 代码如下:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try{
engine.eval("function transform(variable){\n" +
"if(variable == '4'){\n" +
" return true;\n" +
"}else {\n" +
" return false\n" +
" }\n" +
"}");
if (engine instanceof Invocable) {
Invocable in = (Invocable) engine;
System.out.println(in.invokeFunction("add",1,1));
}
}catch(Exception e){
e.printStackTrace();
}
}
读取文件的稍后也记录一下…