I have an array of bytes representing the bytes of a class file.
I am trying to obtain the superclass of the class that is represented by the byte array. Currently, I am using reflection of the ClassLoader class’ “defineClass” method to create a class definition of the class represented by the byte array. I then obtain the superclass by calling getSuperclass() on the newly created Class object.
Based on the superclass of the class that is represented by the byte array I need to perform bytecode transformations. Then end goal is to redefine the class represented by the byte array after its transformations.
The issue is that I cannot redefine the transformed class as its original name because two+ classes with the same name cannot be defined in the same JVM instance.
I really need to be able to make transformations based on the superclass of the class represented by the byte array and really need to redefine the transformed class with its original name.
Is there any way to obtain the superclass of a class while the class is in the form of an array of bytes? Based on the format of the .class file I would assume I could somehow “hackily” determine the superclass without defining the class as a class object and loading it into the JVM but I’m not quite sure where I would begin doing that.
Any suggestions?
Simple, but not very efficient at runtime: Define the class in a new classloader, determine the super type, do your transformations, and define the class in the class loader of your choice. (classes loaded by different class loaders are considered distinct at runtime).
More efficient: Use some library capable of inspecting class files such as Javassist (Tutorial), or write the extraction code yourself (check the class file specification).