java中调⽤js脚本(函数)执⾏最近项⽬开发中⽤到了java调⽤js脚本的需求,在此做⼀下记录:下⾯为kotlin代码
val manager = ScriptEngineManager()
val engine = EngineByName("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 = EngineByName("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();
}
}
js脚本编程入门读取⽂件的稍后也记录⼀下…
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论