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);