package com.moodincode.database_git_compare; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class ScriptEngineTest { public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); /* <dependency> <groupId>org.python</groupId> <artifactId>jython</artifactId> <version>2.7-b1</version> </dependency> */ //PyScriptEngine ScriptEngine engine = manager.getEngineByName("python"); try { //模拟脚本中调用传入的变量 engine.put("test", new ScriptEngineTest()); engine.eval("print \"hello \"+test.test(\"python\")"); } catch (Exception ex) { ex.printStackTrace(); } /* <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>3.0.5</version> <type>pom</type> </dependency> */ //GroovyScriptEngineImpl ScriptEngine engine2 = manager.getEngineByName("groovy"); String HelloLanguage = "def hello(language) {return \"Hello $language\"}"; engine2.put("test", new ScriptEngineTest()); Object eval = engine2.eval(HelloLanguage); eval = engine2.eval("hello(\"Groovy\")"); System.out.println(eval); eval = engine2.eval("test.test2(\"33333#adaadssssssssss#\")"); System.out.println(eval); /* <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-jexl3</artifactId> <version>3.1</version> </dependency> */ //JexlScriptEngine ScriptEngine engine3 = manager.getEngineByName("jexl"); try { engine3.put("test", new ScriptEngineTest()); engine3.eval("test.test(\"jexl\")"); } catch (Exception ex) { ex.printStackTrace(); } /* jdk15以下不需要引入这个依赖,jdk拓展包自带 <dependency> <groupId>org.openjdk.nashorn</groupId> <artifactId>nashorn-core</artifactId> <version>15.4</version> </dependency> */ //NashornScriptEngine ScriptEngine engine4 = manager.getEngineByName("javascript"); //或者ScriptEngine engine4 = manager.getEngineByName("nashorn"); try { engine4.put("test", new ScriptEngineTest2()); Object evalValue = engine4.eval("var j='hello js '+test.test();j;"); System.out.println(evalValue); } catch (Exception ex) { ex.printStackTrace(); } //输出结果为:test //test //hello hello worl====python //Hello Groovy //test //hello worl====33333#adaadssssssssss# //Standard Commons Logging discovery in action with spring-jcl: please remove commons-logging.jar from classpath in order to avoid potential conflicts //test //test //hello js hello worldasssasaaa //Process finished with exit code 0 } public String test() { System.out.println("test"); return "hello worldasssasaaa"; } /** * 暴露变量给脚本调用 * * @param key * @return */ public String test(String key) { System.out.println("test" ); return "hello worl====" + key; } public String test2(String key) { System.out.println("test" ); return "hello worl====" + key; } }
java scriptEngine支持groovy,python,jexl,JavaScript 的交互
于 2024-04-18 19:01:48 首次发布