Java ClassLoader - 将动态加载的 jars 添加到系统类加载器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6617521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:38:42  来源:igfitidea点击:

Java ClassLoader - Adding dynamically loaded jars to the system class loader

javaclassloader

提问by Fozefy

Is there any way to update the system class loader at runtime? After I've dynamically loaded a jar file, is there anything I can do to add the classes/packages loaded from this jar into my system class loader?

有没有办法在运行时更新系统类加载器?在我动态加载了一个 jar 文件之后,我可以做些什么来将从这个 jar 加载的类/包添加到我的系统类加载器中?

The reason I'm trying to do this is that while I've had some success through just passing around my newly created ClassLoader in my own code, I'm having trouble with a third party library (apache-WSIF) that doesn't seem to be working with the passed in ClassLoader.

我尝试这样做的原因是,虽然我通过在我自己的代码中传递我新创建的 ClassLoader 取得了一些成功,但我在使用第三方库 (apache-WSIF) 时遇到了麻烦似乎正在处理传入的 ClassLoader。

回答by Fozefy

I've been able to achieve what I was attempting to do using the following:

我已经能够使用以下方法实现我试图做的事情:

Thread.currentThread().setContextClassLoader(myClassLoader);

Thread.currentThread().setContextClassLoader(myClassLoader);

As discussed in the top answer here: How do you change the CLASSPATH within Java?

正如这里的最佳答案中所讨论的:如何在 Java 中更改 CLASSPATH?

Basically, before calling into the WSIF library all I need to do is make sure I've set my custom classLoader as the contextClassLoader on the current thread.

基本上,在调用 WSIF 库之前,我需要做的就是确保我已将自定义 classLoader 设置为当前线程上的 contextClassLoader。