defineClass(className, byte[], offset, length)
.new CustomClassLoader(Thread.currentThread().getContextClassLoader())
.
So the parent of my CustomClassLoader is the ClassLoader from the current thread.Thread.currentThread().setContextClassLoader()
with my CustomClassLoader.Class.forName(String, true, the CustomClassLoader)
.What did I wrong ? If you need more info, a detailed topic is on my GitHub.
Java classloaders first search the parent classloader before looking in the child.
The loadClass method in ClassLoader performs these tasks, in order, when called to load a class:
- If a class has already been loaded, it returns it.
- Otherwise, it delegates the search for the new class to the parent class loader.
- If the parent class loader does not find the class, loadClass calls the method findClass to find and load the class.
(Understanding Extension Class Loading - Oracle)
If you want to change that order, you need to override the loadClass
method as well but there are many caveats and it's not advisable unless you understand classloading very well.
B
.There are several things to know:
A
via your custom loader, it will delegate to its parent loader, returning a class A
loaded by the parent.A
to B
is resolved, the JVM will always use the parent loader which defined the class A
The last point implies that even if you modify your custom class loader to look up its own classes first instead of following the standard model of querying the parent first, it doesn’t solve the issue if it has no own A
, as then, it still returns the parent’s A
whose references will be resolved using the parent. Since you are invoking defineClass
before asking for A
, the lookup order doesn’t matter at all, as your custom loader has an already defined B
that it returned if anyone ever asked it for B
…
So you could let your custom loader also load and define A
. Or you use Reflection with access override to defineClass
on the system ClassLoader
before it loads B
. The cleanest solution is to implement the class modification logic as a Java Agent which can use the Instrumentation API to intercept and change the definition of B
right at its loading time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With