JUnit 擅長自動化單元測試,但在「互動式測試」、「即時參數調整」、「無 IDE 環境下的腳本執行」場景下力有未逮。BeanShell 是純 Java 實作的動態腳本語言,語法與 Java 幾乎相同,能無縫存取 Java 物件,完美填補此空白。
bsh.Interpreter 是 BeanShell 的核心進入點,提供 REPL 環境與腳本執行能力。
public class TestInt {
public static void main(String[] args) {
bsh.Interpreter.main(args); // 直接啟動標準 Shell
}
}
執行後進入互動模式:
BeanShell 2.0b4 - by Pat Niemeyer
bsh % System.out.println("Hello BeanShell");
Hello BeanShell
bsh %
public static void main(String[] args) throws Throwable {
Reader in = new InputStreamReader(System.in);
PrintStream out = System.out, err = System.err;
boolean interactive = true;
bsh.Interpreter i = new Interpreter(in, out, err, interactive);
// 關鍵:將 Java 物件注入 Shell 命名空間
Collection theObjectReadyForShellUser = new ArrayList();
theObjectReadyForShellUser.add("Str1");
i.set("myObject", theObjectReadyForShellUser); // 變數名 myObject
i.run(); // 阻塞等待使用者輸入
}
Shell 中即可直接操作:
bsh % System.out.println(myObject.get(0));
Str1
bsh %
public static void main(String[] args) throws Throwable {
bsh.Interpreter i = new Interpreter();
String command = JOptionPane.showInputDialog("Input Command(s)");
i.eval(command); // 執行使用者輸入的 Java 代碼片段
}
應用:GUI 應用內建「開發者主控台」、規則引擎動態載入業務規則、熱修復腳本下發執行。
| 特性 | 優勢 |
|---|---|
| Java 語法相容 | Java 開發者零學習成本,可直接複製貼上代碼片段 |
| 無縫 Java 互操作 | 直接存取 JVM 中任何物件、呼叫任何方法、實作任何介面 |
| 輕量級 | 單一 JAR 約 300KB,無額外依賴,嵌入應用極簡單 |
| 動態執行 | 無需編譯,即時見效,適合探索性測試 |
| 安全性可控 | 可自訂 ClassLoader、權限管理器,限制腳本權限 |
BeanShell 雖非最新技術,但在「Java 語法相容性」、「嵌入式腳本化」、「輕量級部署」三者平衡上極具優勢。對於維護舊系統、快速構建管理主控台、實現動態業務規則引擎的團隊,BeanShell 仍是極佳選擇。