Preface:
Java SE 6.0 採納 JSR 223 建議,使得 Java 能夠與眾多 Script 語言協同運作,透過 Java 定義的標準 API,能夠讓 Script 直接存取和控制 Java 的物件,而Java 應用程式當中也能夠直接內嵌 Script 環境。Java SE 6 的 javax.script package 定義了 Script API,裡面共實作了六個介面和六個類別,如下:
- 介面
- 類別
範例01:第一個 Hello World 程式
- package test.scripts;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo1 {
- public static void main(String args[])
- {
- ScriptEngineManager mgr = new ScriptEngineManager(); // 建立一個 Script 管理員
- ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); // 取得 Javascript 引擎
- try {
- jsEngine.eval("print('Hello, world!')"); // 透過 Javascript 引擎解譯 print('hello, world') 命令
- } catch (ScriptException ex) {
- ex.printStackTrace();
- }
- }
- }
- package test.scripts;
- import java.util.List;
- import javax.script.ScriptEngineFactory;
- import javax.script.ScriptEngineManager;
- public class JSDemo2 {
- /**
- * BD: 範例02:列舉 Java 環境支援的 Script 引擎
- * @param args
- */
- public static void main(String[] args) {
- ScriptEngineManager mgr = new ScriptEngineManager();
- List
factories = mgr.getEngineFactories(); - for (ScriptEngineFactory factory : factories) {
- System.out.println("ScriptEngineFactory Info");
- String engName = factory.getEngineName(); // 引擎名稱
- String engVersion = factory.getEngineVersion(); // 引擎版本
- String langName = factory.getLanguageName(); // Script 語言
- String langVersion = factory.getLanguageVersion(); // 語言版本
- System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);
- List
engNames = factory.getNames(); - for (String name : engNames) {
- System.out.printf("\t\tEngine Alias: %s\n", name);
- }
- System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
- }
- }
- }
範例03:搜尋指定的 Script 引擎
- package test.scripts;
- import java.util.List;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineFactory;
- import javax.script.ScriptEngineManager;
- public class JSDemo3 {
- /**
- * BD: 範例03:搜尋指定的 Script 引擎
- * @param args
- */
- public static void main(String[] args) {
- ScriptEngineManager mgr = new ScriptEngineManager();
- List
scriptFactories = mgr.getEngineFactories(); - for (ScriptEngineFactory factory : scriptFactories) {
- String langName = factory.getLanguageName();
- String langVersion = factory.getLanguageVersion();
- if (langName.startsWith("ECMAScript") && langVersion.startsWith("1.6")) { // 比對指定的與名稱和版本
- ScriptEngine engine = factory.getScriptEngine();
- System.out.printf("Engine:%s\n", engine);
- break;
- }
- }
- }
- }
考慮有如下的 js 檔案:
- hellp.js
- var str="Hello world, welcome to the universe.";
- var n=str.indexOf("welcome");
- print(str+" "+n);
- package test.scripts;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.Reader;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo4 {
- /**
- * BD: 範例04:執行外部 javasript 檔案
- * @param args
- */
- public static void main(String[] args) throws Exception {
- ScriptEngineManager engineMgr = new ScriptEngineManager();
- ScriptEngine engine = engineMgr.getEngineByName("ECMAScript");
- InputStream is = new FileInputStream("hello.js");
- try {
- Reader reader = new InputStreamReader(is);
- engine.eval(reader);
- } catch (ScriptException ex) {
- ex.printStackTrace();
- }
- }
- }
範例05:透過 Invocable 介面喚起 Javascript 函數
- package test.scripts;
- import javax.script.Invocable;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo5 {
- /**
- * BD: 範例05:透過 Invocable 介面喚起 Javascript 函數
- * @param args
- */
- public static void main(String[] args) {
- ScriptEngineManager engineMgr = new ScriptEngineManager();
- ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");
- try {
- jsEngine.eval("function sayHello() {" +
- " println('Hello, world!');" +
- "}");
- Invocable invocableEngine = (Invocable) jsEngine;
- invocableEngine.invokeFunction("sayHello");
- } catch (ScriptException ex) {
- ex.printStackTrace();
- } catch (NoSuchMethodException nsme){
- nsme.printStackTrace();
- }
- }
- }
範例06:Script 直接存取 Java 物件
- package test.scripts;
- import java.util.ArrayList;
- import java.util.List;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo6 {
- /**
- * BD: 範例06:Script 直接存取 Java 物件
- * @param args
- */
- public static void main(String args[]) {
- List
namesList = new ArrayList (); - namesList.add("Jill");
- namesList.add("Bob");
- namesList.add("Laureen");
- namesList.add("Ed");
- ScriptEngineManager engineMgr = new ScriptEngineManager();
- ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");
- jsEngine.put("namesListKey", namesList); // 將 java 變數指定給 javascript 環境中的 nameListKey 變數
- System.out.println("Executing in script environment…");
- try {
- // 列印 Java 的 nameList 變數內容,並新增一個 Dana 字串資料到 List 尾端
- jsEngine.eval("var x;" + "var names = namesListKey.toArray();"
- + "for(x in names) {" + " println(names[x]);" + "}"
- + "namesListKey.add(\"Dana\");");
- } catch (ScriptException ex) {
- ex.printStackTrace();
- }
- System.out.println("Executing in Java environment…");
- for (String name : namesList) {
- System.out.println(name);
- }
- }
- }
範例07:透過 Invocable 將參數值傳遞給 Javascript 中的函數
- package test.scripts;
- import java.util.ArrayList;
- import java.util.List;
- import javax.script.Invocable;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo7 {
- /**
- * BD: 範例07:透過 Invocable 將參數值傳遞給 Javascript 中的函數
- * @param args
- */
- public static void main(String[] args) {
- List
namesList = new ArrayList (); - namesList.add("Jill");
- namesList.add("Bob");
- namesList.add("Laureen");
- namesList.add("Ed");
- ScriptEngineManager engineMgr = new ScriptEngineManager();
- ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");
- Invocable invocableEngine = (Invocable) jsEngine;
- try {
- System.out.printf("\t[Info] Execute in JS:\n");
- jsEngine.eval("function printNames1(namesList) {" + " var x;"
- + " var names = namesList.toArray();"
- + " for(x in names) {" + " println(names[x]);" + " }"
- + "}" + "function addName(namesList, name) {"
- + " namesList.add(name);" + "}");
- invocableEngine.invokeFunction("printNames1", namesList);
- invocableEngine.invokeFunction("addName", namesList, "Dana");
- System.out.printf("\t[Info] Execute in Java:\n");
- for(String name:namesList) System.out.println(name);
- } catch (ScriptException ex) {
- ex.printStackTrace();
- } catch (NoSuchMethodException ex) {
- ex.printStackTrace();
- }
- }
- }
範例08:script 使用 Java 的 package
- package test.scripts;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class JSDemo8 {
- /**
- * BD: 範例08:script 使用 Java 的 package
- * @param args
- */
- public static void main(String[] args) {
- ScriptEngineManager engineMgr = new ScriptEngineManager();
- ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");
- try {
- jsEngine.eval("importPackage(javax.swing);" + "var optionPane = "
- + " JOptionPane.showMessageDialog(null, 'Hello, world!');");
- } catch (ScriptException ex) {
- ex.printStackTrace();
- }
- }
- }
* W3Schools.com > JavaScript tutorial
* jrunscript - command line script shell
* Wiki > Rhino (JavaScript engine)
沒有留言:
張貼留言