Changing default classloader behavior in Java

I am trying to load one class using custom logic (i.e. I want to change the class implementation in my libraries using a special version).

I would like to create my own custom classloader, which is a proxy to the default bootloader. However, it looks like my default class loader: sun.misc.Launcher.AppClassLoader is not displayed - this means that I can not extend it.

Any solutions for creating a single class loader that are strong enough to replicate the behavior of my existing class loader when matched in one particular class will be highly appreciated.

Please note that I tried using

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

However, this does not work, that is, classes loaded into the stream do not always start my custom classloader.


CONTEXT

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

+4
source share
1 answer

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

If the source LibraryClass already in the class path, this cannot be done using a special class loader due to the hierarchy of the class loader (see Java class loading mechanism ).

One possible solution is to place the jar that contains your custom LibraryClass at the very beginning of the class path. Then your custom class will be loaded in favor of the original.

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

0
source

Source: https://habr.com/ru/post/1488984/


All Articles