程式扎記: [ Java 文章收集 ] Java SE 6.0 內建 Javascript 引擎測試

標籤

2010年9月15日 星期三

[ Java 文章收集 ] Java SE 6.0 內建 Javascript 引擎測試


轉載自 這裡
前言 :
Java SE 6.0 採納 JSR 223 建議,使得 Java 能夠與眾多 Script 語言協同運作,透過 Java 定義的標準 API,能夠讓 Script 直接存取和控制 Java 的物件,而Java 應用程式當中也能夠直接內嵌 Script 環境。Java SE 6 的 javax.script package 定義了 Script API,裡面共實作了六個介面和六個類別,如下 :
- 介面
Bindings
Compilable
The optional interface implemented by ScriptEngines whose methods compile scripts to a form that can be executed repeatedly without recompilation. 

Invocable
The optional interface implemented by ScriptEngines whose methods allow the invocation of procedures in scripts that have previously been executed.

ScriptContext
The interface whose implementing classes are used to connect Script Engines with objects, such as scoped Bindings, in hosting applications. Each scope is a set of named attributes whose values can be set and retrieved using the ScriptContext methods. ScriptContexts also expose Readers and Writers that can be used by the ScriptEngines for input and output.

ScriptEngine
ScriptEngine is the fundamental interface whose methods must be fully functional in every implementation of this specification.

ScriptEngineFactory
ScriptEngineFactory is used to describe and instantiate ScriptEngines.

- 類別
AbstractScriptEngine
Provides a standard implementation for several of the variants of the eval method.

CompiledScript
Extended by classes that store results of compilations. State might be stored in the form of Java classes, Java class files or scripting language opcodes. The script may be executed repeatedly without reparsing.

ScriptEngineManager
The ScriptEngineManager implements a discovery and instantiation mechanism for ScriptEngine classes and also maintains a collection of key/value pairs storing state shared by all engines created by the Manager. This class uses the service provider mechanism to enumerate all the implementations of ScriptEngineFactory.

SimpleBindings
A simple implementation of Bindings backed by a HashMap or some other specified Map.

SimpleScriptContext
Simple implementation of ScriptContext.

ScriptException
The generic Exception class for the Scripting APIs. Checked exception types thrown by underlying scripting implementations must be wrapped in instances of ScriptException. The class has members to store line and column numbers and filenames if this information is available.

範例說明 :
底下將會帶幾個範例, 來說明這個 Java 的 JavaScript 引擎能夠達成的工作 :
- 範例01 : 第一個 Hello World 程式, 直接將 JavaScript 代碼丟入 JS Engine 的 eval 函式執行.
- JSHello.java 代碼
  1. package john.js;  
  2.   
  3. import javax.script.*;  
  4.   
  5. public class JSHello {  
  6.     public static void main(String args[]) {  
  7.         ScriptEngineManager mgr = new ScriptEngineManager(); // 建立一個 Script 管理員  
  8.         ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); // 取得 Javascript 引擎  
  9.         try {  
  10.           jsEngine.eval("print('Hello, world!')"); // 透過 Javascript 引擎解譯 print('hello, world') 命令  
  11.         } catch (ScriptException ex) {  
  12.             ex.printStackTrace();  
  13.         }      
  14.     }  
  15. }  

- 範例02:執行外部 javasript 檔案, 這裡是直接把含 JavaScript 代碼(Hello.js) 的內容透過 InputStream 丟給 JS Engine 的 eval API 執行.
- JSRunExtendFile.java 代碼 :
  1. package john.js;  
  2.   
  3. import javax.script.*;  
  4. import java.io.*;   
  5.   
  6. public class JSRunExtendFile {  
  7.     public JSRunExtendFile() {  
  8.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  9.         ScriptEngine engine = engineMgr.getEngineByName("ECMAScript");        
  10.         try {  
  11.             InputStream is = new FileInputStream(new File("Hello.js"));  
  12.             Reader reader = new InputStreamReader(is);  
  13.             engine.eval(reader);  
  14.         } catch (ScriptException ex) {  
  15.             ex.printStackTrace();  
  16.         } catch (Exception e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20.   
  21.     public static void main(String[] args) {  
  22.         JSRunExtendFile ref = new JSRunExtendFile();     
  23.     }  
  24. }  

- 範例03:透過 Invocable 介面喚起 Javascript 函數.
- JSInvokeFunction.java 代碼 :
  1. package john.js;  
  2.   
  3. import javax.script.*;  
  4.   
  5. public class JSInvokeFunction {  
  6.   
  7.     public static void main(String[] args) {  
  8.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  9.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  10.         try {  
  11.             jsEngine.eval("function sayHello() {"  
  12.                     + "  println('Hello, world!');" + "}");  
  13.             Invocable invocableEngine = (Invocable) jsEngine;  
  14.             invocableEngine.invokeFunction("sayHello");  
  15.         } catch (ScriptException ex) {  
  16.             ex.printStackTrace();  
  17.         } catch (NoSuchMethodException nsme) {  
  18.             nsme.printStackTrace();  
  19.         }  
  20.     }  
  21. }  

- 範例04:Script 直接存取 Java 物件
- JSAccessJavaObject.java 代碼 :
  1. package john.js;  
  2.   
  3. import javax.script.*;  
  4. import java.util.*;  
  5.   
  6. public class JSAccessJavaObject {  
  7.   
  8.     public static void main(String[] args) {  
  9.         List namesList = new ArrayList();  
  10.         namesList.add("Jill");  
  11.         namesList.add("Bob");  
  12.         namesList.add("Laureen");  
  13.         namesList.add("Ed");  
  14.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  15.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  16.         jsEngine.put("namesListKey", namesList); // 將 java 變數指定給 javascript 環境中的  
  17.                                                     // nameListKey 變數  
  18.         System.out.println("Executing in script environment...");  
  19.         try {  
  20.             // 列印 Java 的 nameList 變數內容,並新增一個 Dana 字串資料到 List 尾端  
  21.             jsEngine.eval("var x;" + "var names = namesListKey.toArray();"  
  22.                     + "for(x in names) {" + "  println(names[x]);" + "}"  
  23.                     + "namesListKey.add(\"Dana\");");  
  24.         } catch (ScriptException ex) {  
  25.             ex.printStackTrace();  
  26.         }  
  27.         System.out.println("Executing in Java environment...");  
  28.         for (String name : namesList) {  
  29.             System.out.println(name);  
  30.         }  
  31.     }  
  32. }  

範例05:透過 Invocable 將參數值傳遞給 Javascript 中的函數
- JSPassValueToFunction.java 代碼 :
  1. package john.js;  
  2.   
  3. import javax.script.*;  
  4. import java.util.*;  
  5.   
  6. public class JSPassValueToFunction {  
  7.   
  8.     public static void main(String[] args) {  
  9.         List namesList = new ArrayList();  
  10.         namesList.add("Jill");  
  11.         namesList.add("Bob");  
  12.         namesList.add("Laureen");  
  13.         namesList.add("Ed");  
  14.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  15.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  16.         Invocable invocableEngine = (Invocable) jsEngine;  
  17.         try {  
  18.             jsEngine.eval("function printNames1(namesList) {" + "  var x;"  
  19.                     + "  var names = namesList.toArray();"  
  20.                     + "  for(x in names) {" + "    println(names[x]);" + "  }"  
  21.                     + "}" + "function addName(namesList, name) {println('addName: Add '+name);"  
  22.                     + "  namesList.add(name);" + "}");  
  23.             invocableEngine.invokeFunction("printNames1", namesList);  
  24.             invocableEngine.invokeFunction("addName", namesList, "Dana");  
  25.         } catch (ScriptException ex) {  
  26.             ex.printStackTrace();  
  27.         } catch (NoSuchMethodException ex) {  
  28.             ex.printStackTrace();  
  29.         }  
  30.     }  
  31. }  

補充說明 :
純種 Java 與 Javascript 結合
將Script整合進應用程式所能達到的彈性空間的確十分強大,如果能在我們開發的系統也提供Scripting的能力,除了強化擴充性之外,整個系統的質感也是提升不少…爽度up!up!
但以往要達成這目標,有個難處,就是解釋並執行Script用的Interpreting Engine那裡來,自己寫顯然是太累了…。
Java 6這回帶來了好消息:Scripting API,在Java系統中結合Scripting再也不難了,你只需要import javax.script.*; ...

Javascript教學文章庫
Javascript(本名為Livescript, 為網景Netscape開發出來的語言)。 你所看到讓文字和圖片跟著滑鼠跑、日曆、漸層效果很多都是用Javascript寫成的。這個語言主要讓網頁更活潑, 更有互動性, 好處是幾乎所有的瀏覽器都支援...
This message was edited 9 times. Last update was at 09/09/2010 15:50:31

沒有留言:

張貼留言

網誌存檔