【问题标题】:Beanshell will not allow me to add jars to the "default" JRE classloader?Beanshell 不允许我将 jars 添加到“默认”JRE 类加载器?
【发布时间】:2011-09-23 23:19:43
【问题描述】:

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

  1. 在调用 Beanshell 和 Beanshell 之前定义 Classpath 的位置 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!");
}

【问题讨论】:

    标签: java classloader beanshell dynamic-class-loaders groovyclassloader


    【解决方案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
    

    【讨论】:

    • 是的,这行得通。我不敢相信我忽略了这一点。非常非常感谢!
    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2013-03-15
    • 2012-06-11
    • 1970-01-01
    • 2014-08-27
    相关资源
    最近更新 更多