Is it possible to change the inheritance hierarchy of class objects at runtime with reflection?
My situation is I have:
SuperClass
MiddleClass extends SuperClass
BottomClass extends SuperClass
I would like to use reflection at runtime to change BottomClass to extend MiddleClass. Is this possible?
THanks
The closest you can get to this with Java is instrumentation. Basically you write some Java classes which are given the series of bytes which define a class, muck around with the byte code, and return the modified class file byte array. You then package these classes up in a JAR file and tell the JVM to use them, either on the command line or by putting an attribute into the manifest file of the instrumentation JAR file.
Of course, if you do this, you'd want to use some byte code manipulation library like ASM.
EDIT: If the class you're interested in implements interfaces you might want to take a look at dynamic proxy classes via java.lang.reflect.Proxy. This has the disadvantage that pieces of code which you didn't write which do new ClassOfInterest()
are unaffected, but has the advantages of:
SecurityManager
issues.No, it's not possible through reflection becuase reflection is used to analyze the existing code, not to change it.
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