Change java class superclass with reflection

Is it possible to change the inheritance hierarchy of class objects at runtime with reflection?

My situation is with me:

Superclass

MiddleClass extends SuperClass

BottomClass extends SuperClass

I would like to use reflection at runtime to modify BottomClass to extend MiddleClass. Is it possible?

thanks

+4
source share
4 answers

No, this is not possible due to reflection, because reflection is used to analyze existing code, and not to modify it.

+4
source

The closest thing you can get is with Java: instrumentation . Basically you write some Java classes that are given a series of bytes that define the class, quench around with byte code, and return an array of bytes of the modified class. You then pack these classes into a JAR file and instruct the JVM to use them either on the command line or by adding an attribute to the manifest file of the toolkit JAR file.

Of course, if you do this, you need to use some byte manipulation library, such as ASM .

EDIT . If the class you are interested in implements interfaces, you can take a look at dynamic proxy classes through java.lang.reflect.Proxy . This has the disadvantage that code snippets that you don’t write that do new ClassOfInterest() are not affected, but have the following advantages:

  • Being a lot easier than changing the byte code of classes.
  • You can dynamically choose that different proxy instances act as if they have a different superclass.
  • You do not need to worry about any SecurityManager issues.
+5
source

Inheritance is static, so it cannot be changed at runtime.

However, you can make a SuperClass interface or use delegation instead of inheritance.

0
source

it's impossible. For example, if you already have a BottomClass object and you are trying to change the superclass, what will happen to this object? it's impossible...

-1
source

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


All Articles