How to load modified superclass in Java?

  • I have a class A that extends B.
  • I created a CustomClassLoader that extends ClassLoader for use defineClass(className, byte[], offset, length).
  • I have installed new CustomClassLoader(Thread.currentThread().getContextClassLoader()). So the parent of my CustomClassLoader is the ClassLoader from the current thread.
  • I modified class B using the ASM structure. I wrote my modified class in a .class file and use a decompiler to make sure it works. And it works.
  • I added a modified class B to my CustomClassLoader
  • I installed Thread.currentThread().setContextClassLoader()using my CustomClassLoader.
  • I load A using Class.forName(String, true, the CustomClassLoader).
  • But the loaded class B seems to be the original class.

What did I misunderstand? If you need more information, a detailed topic is on my GitHub .

+4
source share
2 answers

Java class loaders first look for the parent class loader before looking in it.

The loadClass method in ClassLoader performs these tasks so that when called to load the class:

  • If the class is already loaded, it returns it.
  • Otherwise, it delegates the search for the new class to the parent class loader.
  • If the loader of the parent class does not find the class, loadClass calls the findClass method to find and load the class.

( Understanding Extension Class Loading - Oracle)

, loadClass, , , .

  • - , B.
+2

, :

  • , . ; , . . , . , , .
  • Erwin Bolwidt, A , A, .
  • JVM . , A B , JVM , A

, , , , , A, A, . defineClass A, , B, , - B...

, A. Reflection defineClass ClassLoader, B. - Java-, API- Instrumentation B .

+1

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


All Articles