Java SE6中添加了脚本语言API,可通过java进行灵活的操作脚本语言。以下是示例代码:
//操作属性 public static void attributeInBindings() throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); ScriptContext context = engine.getContext(); context.setAttribute("name", "Alex", ScriptContext.GLOBAL_SCOPE); engine.eval("println(name);");//输出Alex }
//调用方法 public static void invokeFunction() throws ScriptException, NoSuchMethodException{ ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); String scriptText = "function greet(name){println('hello,'+name);}"; engine.eval(scriptText); Invocable invocable = (Invocable)engine; invocable.invokeFunction("greet", "wenxin"); }
//调用脚本中对象成员方法 public static void invokeMethod() throws ScriptException, NoSuchMethodException{ ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); String scriptText = "var obj={getGreeting:function(name){return 'hello,'+name;}};"; engine.eval(scriptText); Invocable invocable = (Invocable)engine; Object scope = engine.get("obj"); Object result = invocable.invokeMethod(scope, "getGreeting", "dwen"); System.out.println(result); }
//进行脚本编译{解释执行的方式运行脚本的速度比编译之后再运行会慢些,当一段脚本需要被多次重复 //执行时,可以对脚本进行编译。编译之后脚本在执行时不需重复解析} public static void compliedScript() throws ScriptException, NoSuchMethodException{ CompiledScript script = null; ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); String scriptText = "function getGreeting(name){println('hello,'+name);}"; if (engine instanceof Compilable) {//实例判断,因为不是所有脚本语言都支持编译 script = ((Compilable) engine).compile(scriptText); script.eval(); Invocable invocable = (Invocable)engine; invocable.invokeFunction("getGreeting", "wenxin"); } }
操作实现java接口:
public interface IGreet { public String getGreeting(String name); }
//在脚本中实现java接口 public static void useInterface() throws ScriptException{ ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); String scriptText = "function getGreeting(name){return 'hello,'+name;}"; engine.eval(scriptText); Invocable invocable = (Invocable)engine; IGreet greet = invocable.getInterface(IGreet.class); System.out.println(greet.getGreeting("接口")); }