3

我有一個關於Beanshell的問題,我無法在任何地方找到答案。我只能夠在1 2的方式運行的BeanShell腳本:Beanshell不會允許我將JAR添加到「默認」JRE類加載器中?

  1. 類路徑在哪裏被調用的BeanShell和BeanShell的定義之前使用 JRE的默認類加載器。

  2. 如果沒有classpath中被定義爲所有BeanShell的開始前,然後我用 addClassPath()importCommands()動態構建BeanShell中的類加載器中的類路徑 。此方法似乎不會繼承作爲默認JRE類裝入器的一部分的罐子 。

多次試驗後,我瞭解到,我無法啓動的腳本來預先定義的類路徑,然後能夠通過使用addClassPath()添加到classpath中。我不知道這是否如設計或如果我做錯了

很容易看出自己的問題是什麼。例如,下面是腳本:

::Test.bat (where bsh.jar exists in JRE/lib/ext directory) 
@echo off 
set JAVA_HOME=C:\JDK1.6.0_27 
:: first invoke: this first command works 
%JAVA_HOME%\jre\bin\java.exe bsh.Interpreter Test.bsh 
:: second invoke: this command fails 
%JAVA_HOME%\jre\bin\java.exe -cp ant.jar bsh.Interpreter Test.bsh 

第二調用導致此錯誤:

Evaluation Error: Sourced file: Test.bsh : Command not 
found: helloWorld() : at Line: 5 : in file: Test.bsh : helloWorld () 

TEST.BAT啓動這個腳本的BeanShell:

// Test.bsh 
System.out.println("Trying to load commands at: " + "bin"); 
addClassPath("bin"); 
importCommands("bin"); 
helloWorld(); 

而且,這是我的helloWorld .bsh腳本:

// File: helloWorld.bsh 
helloWorld() { 
    System.out.println("Hello World!"); 
} 

回答

1

Test.bsh有微小誤差:importCommands查找一個名爲類路徑,並從那裏加載所有.bsh文件「bin」目錄,所以你應該添加到addClassPath什麼是當前目錄:

// Test.bsh 
System.out.println("Trying to load commands at: " + "bin"); 
addClassPath("."); // current directory 
importCommands("bin"); 
helloWorld(); 

的代碼在第一種情況下工作,因爲當前目錄在默認的系統類路徑中。問題是-cp開關覆蓋默認的類路徑,因此importCommands不再有任何方法可以找到bin目錄。

另外,您可以添加.到classpath的JVM級別:

%JAVA_HOME%\jre\bin\java.exe -cp .;ant.jar bsh.Interpreter Test.bsh 
+0

是的,這工作。我不敢相信我忽略了這一點。非常非常感謝你! – djangofan