Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change java class superclass with reflection

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

like image 238
mike Avatar asked Nov 05 '11 20:11

mike


2 Answers

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:

  1. Being a lot easier than modifying the byte code of classes.
  2. You can dynamically choose to make different instances of the proxies act like they have different superclassess.
  3. You don't have to worry about any SecurityManager issues.
like image 77
Matthew Cline Avatar answered Nov 11 '22 11:11

Matthew Cline


No, it's not possible through reflection becuase reflection is used to analyze the existing code, not to change it.

like image 43
Malcolm Avatar answered Nov 11 '22 11:11

Malcolm