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