3

どこにも答えが見つからないBeanshellに関する質問があります。Beanshell スクリプトを実行できるのは、次の 2 つの方法のうちの 1 つだけです。

  1. クラスパスは Beanshell を呼び出す前に定義され、Beanshell は JRE のデフォルト クラスローダーを使用します。

  2. Beanshell を起動する前にクラスパスがまったく定義されていない場合、and を使用 addClassPath()importCommands()て Beanshell のクラスローダー内でクラスパスを動的に構築します。このメソッドは、デフォルトの JRE クラスローダーの一部であった jar を継承していないようです。

多くの実験の後、事前定義されたクラスパスを使用してスクリプトを開始できず、を使用してクラスパスに追加できないことがわかりましたaddClassPath()これが設計どおりなのか、それとも何か間違っているのかわかりません。

私の問題が何であるかを自分で確認するのは非常に簡単です。たとえば、スクリプトは次のとおりです。

::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

2 番目の呼び出しでは、次のエラーが発生します。

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!");
}
4

1 に答える 1

1

Test.bshわずかなエラーがあります。importCommandsクラスパスで「bin」というディレクトリを探し、そこからすべての .bsh ファイルをロードするため、追加する必要がaddClassPathあるのは現在のディレクトリです。

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

現在のディレクトリがデフォルトのシステム クラス パスにあるため、コードは最初のケースで機能します。問題は、-cpスイッチがデフォルトのクラスパスをオーバーライドするため、ディレクトリimportCommandsを見つける方法がなくなることです。bin

.または、JVM レベルでクラスパスに追加することもできます。

%JAVA_HOME%\jre\bin\java.exe -cp .;ant.jar bsh.Interpreter Test.bsh
于 2012-02-09T14:36:09.193 に答える