java 包含罐子的罐子中的类的替换系统类加载器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5380275/
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 10:51:32  来源:igfitidea点击:

Replacement System Classloader for Classes In Jars containing Jars

javajarclassloader

提问by Olaseni

So far, the examples I have seen for custom ClassLoaders involve subclassing the URLClassLoader, and using that specific instance to load classes in resources.

到目前为止,我看到的自定义 ClassLoader 示例涉及对 URLClassLoader 进行子类化,并使用该特定实例加载资源中的类。

I have tried in vain to look for alternative methods to replace the SystemClassLoader, so that my ClassLoader can be consulted for classes not located in the classpath.

我曾尝试寻找替代方法来替换 SystemClassLoader,但徒劳无功,以便可以咨询我的 ClassLoader 以查找不在类路径中的类。

I tried Thread.currentThread().setContextClassLoader, but it doesn't seem to work.

我试过了Thread.currentThread().setContextClassLoader,但似乎不起作用。

Is it even possible?

甚至有可能吗?

回答by Xyene

Though this is an old question, there is indeed a way to replace the system ClassLoader. You might get more than you bargained for, however, with reflection.

虽然这是一个老问题,但确实有一种方法可以替换系统ClassLoader。但是,通过反思,您可能会得到比讨价还价更多的东西。

        Field scl = ClassLoader.class.getDeclaredField("scl"); // Get system class loader
        scl.setAccessible(true); // Set accessible
        scl.set(null, new YourClassLoader()); // Update it to your class loader

This should work on the Oracle JVM.

这应该适用于 Oracle JVM。

回答by Tarlog

Run JVM with java.system.class.loaderproperty:

使用java.system.class.loader属性运行 JVM :

java -Djava.system.class.loader=myClassLoader myApplication