gpt4 book ai didi

java - 使用类加载器在 java 程序中运行可执行 jar 文件

转载 作者:行者123 更新时间:2023-12-03 01:43:37 25 4
gpt4 key购买 nike

我听说您可以使用 Process 或使用 ClassLoaders 运行其他 java 文件。

我有一个可执行 jar 'test.jar',其主类名为 Test

我找到了一种使用 Process 运行的方法。我需要知道如何使用类加载器来做到这一点。

Process p = Runtime.getRuntime().exec("java -jar test.jar");
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
synchronized (p) {
p.waitFor();
}
int b=0;
while((b=bis.read()) >0){
System.out.print((char)b);
}

最佳答案

一些帮助您入门的代码,基本上按照@Felipe所说的进行。

请记住,这并不完全相同。你没有产生一个新的进程,只是一个新的线程;你可能会遇到一些巨大的类加载问题; Test.jar 文件中的 System.exit() 之类的内容也会导致容器程序终止,等等。

File f = new File("Test.jar");
ClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() }, null);
final Class<?> claxx = cl.loadClass("my.package.Test");
final Method main = claxx.getMethod("main", String[].class);

Thread th = new Thread(new Runnable() {
@Override
public void run() {
try {
main.invoke(claxx, new Object[] { new String[] { "Param1", "Param2" } });
} catch (Throwable th) {
// TODO
}
}
});

th.setContextClassLoader(cl);
th.start();

th.join();

关于java - 使用类加载器在 java 程序中运行可执行 jar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214678/

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