java SE6中对常用的脚本语言做了支持。
可供使用者在java代码中执行脚本语言,还可以利用get("key"),put("key","value")与其交互,并可以动态调用脚本。
package com.test; import java.util.List; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Demo { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); // 得到所有的引擎工厂 List<ScriptEngineFactory> list = manager.getEngineFactories(); for (ScriptEngineFactory factory : list) { System.out.println("支持的脚本语言"+factory.getNames()); // 支持的脚本语言[js, rhino, JavaScript, javascript, ECMAScript, ecmascript] } // 得到常用的javascript脚本 ScriptEngine engine = manager.getEngineByName("javascript"); try { // 执行脚本 System.out.println(engine.eval("2+3*2")); // 8 System.out.println(engine.eval("(true||false)&&true")); //true // 和脚本交互 engine.put("name", "123456"); engine.eval("var out = '';" + "for(i=0;i<name.length;i++){" + " out = name.charAt(i)+ out}"); String name = (String)engine.get("out"); System.out.println("name:"+name); // 动态调用脚本语言(脚本引擎得实现Invocable接口) String str = "abcdef"; if(engine instanceof Invocable){ engine.eval("function str1(name){" + "var out = '';" + "for(i=0;i<name.length;i++){" + " out = name.charAt(i)+ out}" + " return out;}" + "function str2(name){" + " return 123}"); Invocable invocable = (Invocable) engine; try { Object obj = invocable.invokeFunction("str1", "123456"); System.out.println("obj:"+obj); } catch (NoSuchMethodException e) { e.printStackTrace(); } } // 动态实现接口 engine.eval("function run(){" + "print('异步调用')}"); Invocable invocable = (Invocable) engine; // 让其实现Runnable接口 Runnable runnable = invocable.getInterface(Runnable.class); // 启动线程 Thread t = new Thread(runnable); t.start(); } catch (ScriptException e) { e.printStackTrace(); } } }