天天看點

從你的應用程式中調用BeanShell

在你的應用程式中通過建立 BeanShell 的解釋器以及使用 eval() 和 source() 指令來為文本指派或者運作腳本。你可以通過 set() 方法将變量的引用傳遞給你想在腳本中使用的對象而後通過 get() 方法取得結果。

執行個體一:

import bsh.Interpreter; 

Interpreter i = new Interpreter(); // 構造 interpreter 

i.set("foo", 5); // 設定變量 

i.set("date", new Date() ); 

Date date = (Date)i.get("date"); // 重獲變量 

// 表達式求值并得到結果 

i.eval("bar = foo*10"); 

System.out.println( i.get("bar") ); 

// 從外部腳本檔案獲得源碼 

i.source("somefile.bsh"); 

運作效果:

<a href="http://blog.51cto.com/attachment/201112/200306288.jpg" target="_blank"></a>

說明:

類 Interpreter 是 BeanShell 的腳本解釋器。一個Interpreter 執行個體可以被用來獲得腳本源碼(比如本文第二個例子)以及給語句或者表達式進行評估。API見 http://www.beanshell.org/javadoc/index.html

 執行個體二:

在 JEdit 中編輯一段 BeanShell 腳本,檔案名為“somefile.bsh”。使用 Interpreter.source(bsh檔案) 方法可以調用到 BeanShell 的資源。

<a target="_blank" href="http://blog.51cto.com/attachment/201112/102015494.jpg"></a>

使用 BeanShell 工作空間調用“somefile.bsh”的腳本檔案。注意調用路徑,目前的執行個體兩者位于同目錄。

<a target="_blank" href="http://blog.51cto.com/attachment/201112/102126787.jpg"></a>

運作結果:

<a target="_blank" href="http://blog.51cto.com/attachment/201112/102208267.jpg"></a>

本文轉自 tongqiuyan  51CTO部落格,原文連結:http://blog.51cto.com/tongqiuyan/745041

繼續閱讀