Modifying behaviour of default classloader in Java

I am attempting to load a single class using custom logic (ie I want to swap out the implementation of a class in my libraries with a custom version).

I'd like to create my own, custom classloader, which proxies to the default classloader. However, It appears that my default classloader: sun.misc.Launcher.AppClassLoader , is not visible - meaning that I cannot extend it.

Any solutions for creating a single classloader which is robust enough to replicate behaviour of my existing classloader while subbing in one particular class would be much appreciated.

Note that I've tried using

Thread current = Thread.currentThread();
current.setContextClassLoader(newOne);

However, this appears not to work, ie, the classes loaded in the thread are not always triggering my custom classloader.


CONTEXT

I want invocations of "new LibraryClass()" to use a custom implementation of this class - where the "new ..." invocation is in a jar file which not under my control.


So, I think you want to replace the LibraryClass by your custom version using the same fully qualified name, right?

If the original LibraryClass is already on the class path, it will be impossible to do this with a custom classloader due to the classloader hierarchy (see The Java Class Loading Mechanism).

One possible solution is to put the jar, that contains your custom LibraryClass , on the very beginning of the classpath. Your custom class will then be loaded in favor for the original one.

This will not work, if the LibraryClass is a bootstrap or extension class.

链接地址: http://www.djcxy.com/p/44394.html

上一篇: java.lang.NoClassDefFoundError,Ant任务无法在jar中的jar中看到类

下一篇: 在Java中修改默认类加载器的行为