java - Beanshell 不允许我将 jar 添加到 "default"JRE 类加载器?

标签 java classloader beanshell dynamic-class-loaders groovyclassloader

我有一个关于 Beanshell 的问题我无法在任何地方找到答案。我只能以两种方式中的一种运行 Beanshell 脚本:

  1. 在调用 Beanshell 之前定义了 Classpath,Beanshell 使用 JRE 默认类加载器。

  2. 在启动 Beanshell 之前根本没有定义类路径,然后我使用 addClassPath()importCommands() 动态构建类路径 在 Beanshell 的类加载器中。这个方法好像没有继承一个jar 这是默认 JRE 类加载器的一部分。

经过多次试验,我发现我无法使用预定义的类路径启动脚本,然后使用 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

第二次调用导致此错误:

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

最佳答案

您的 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

关于java - Beanshell 不允许我将 jar 添加到 "default"JRE 类加载器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535802/

相关文章:

java - JMeter 返回上一个采样器

java - 导入 Picasso 库问题

java - GWT RPC 如何在其有效负载中编码 java.lang.Long 值?

java - 使用 WildFly 中另一个模块的 JAXBContext 进行解码

javascript - JMeter 使用传入的参数来控制线程组

java - 使用 startTime 和 testDuration 计算 endTime

java - 从另一个类调用 MainActivity 的方法?

java - 如何制作圆角方形组图标而不是圆形组图标

java - Class.forName 调用后如何释放内存?

java - 使用自定义类加载器加载资源包