Java执行JavaScript脚本

demo

//注入函数
StringBuilder scriptContent = new StringBuilder();

scriptContent.append("function run(){");
scriptContent.append("return 123");
scriptContent.append("}");
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("js");

engine.eval(scriptContent.toString());
Invocable inv = (Invocable)engine;
Object result = inv.invokeFunction("run");
System.out.println(result);

js脚本中执行Java方法

//注入函数
StringBuilder scriptContent = new StringBuilder();

scriptContent.append("function run(){");
scriptContent.append("log.info(123123);");
scriptContent.append("return 123;");
scriptContent.append("}");
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("js");

IFunction function = new LogFunction();
engine.put(function.getVarName(),function);

engine.eval(scriptContent.toString());
Invocable inv = (Invocable)engine;
Object result = inv.invokeFunction("run");
System.out.println(result);

posted @ 2022-07-12 17:51  fight139  阅读(856)  评论(0编辑  收藏  举报