public static void main(String[] arags){ try{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); StringBuffer script = new StringBuffer(); script.append("var a = 0;"); // script.append("obj.r = 0;"); // script.append("obj.hello = function(name){print('hello, '+name);}"); script.append("a = eval('1==1 && 1==1');"); //执行这段script脚本 engine.eval(script.toString()); // javax.script.Invocable 是一个可选的接口 // 检查你的script engine 接口是否已实现! // 注意:JavaScript engine实现了Invocable接口 Invocable inv = (Invocable) engine; // 获取我们想调用那个方法所属的js对象 Object obj = engine.get("a"); System.out.println(obj); } catch (Exception ex){ ex.printStackTrace(); } }