gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:26 24 4
gpt4 key购买 nike

我有一个关于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com