jdk1.6开始就提供了动态脚本语言诸如JavaScript动态的支持。这无疑是一个很好的功能,毕竟Java的语法不是适合成为动态语言。而JDK通过执行JavaScript脚本可以弥补这一不足。这也符合“Java虚拟机不仅仅是Java一种语言的虚拟机“这一目标。
ScriptEngine功能强大,基本能实现笔者所能想到的Java与JavaScript交互的需求。而且十分的方便简洁。jdk1.8又对ScriptEngine接口进行了一定改变,因此,在jdk1.8能运行的代码,在1.6中可能会报错,反之亦然。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| public void test2() { ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> factories = manager.getEngineFactories(); for (ScriptEngineFactory factory: factories){ System.out.println(factory.getEngineName()); System.out.println(factory.getEngineVersion()); System.out.println(factory.getLanguageName()); System.out.println(factory.getLanguageVersion()); System.out.println(factory.getExtensions()); System.out.println(factory.getMimeTypes()); System.out.println(factory.getNames()); } }
Oracle Nashorn 1.8.0_77 ECMAScript ECMA - 262 Edition 5.1 [js] [application/javascript, application/ecmascript, text/javascript, text/ecmascript] [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript]
public void test2() { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); try { String str="1+2*(3+4)"; System.out.println(engine.eval(str)); } catch (ScriptException ex) { ex.printStackTrace(); } }
public void test(String name) { ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("js"); try { String script = "function say(){ return 'hello,'"+name+"; }"; se.eval(script); Invocable inv2 = (Invocable) se; String res=(String)inv2.invokeFunction("say",name); System.out.println(res); } catch(Exception e) { e.printStackTrace(); } }
public void testScriptVariables() { ScriptEngineManager sem=new ScriptEngineManager(); ScriptEngine engine=sem.getEngineByName("js"); File file=new File("c:\\1.txt"); engine.put("f", file); try { engine.eval("println('path:'+f.getPath())"); } catch (ScriptException e) { e.printStackTrace(); } }
public void testScriptInterface() throws ScriptException { ScriptEngineManager sem=new ScriptEngineManager(); ScriptEngine engine=sem.getEngineByName("js"); String script="var obj=new Object();obj.run=function(){println('test thread')}"; engine.eval(script); Object obj=engine.get("obj"); Invocable inv=(Invocable)engine; Runnable r=inv.getInterface(obj,Runnable.class); Thread t=new Thread(r); t.start(); }
|