How to extend a class at runtime with reflection

Imagine that I have two classes A and B, B extends A as

class B extends A { .... } 

However, in my case, class A is encrypted and can only be loaded by my ClassLoader at run time (at compile time A.class cannot be recognized as a .class file because it is encrypted). This means that class A does not exist at compile time.

My questions:

  • how to write code for class B since some methods override methods in class A?
  • how can I indicate that class B extends to class A at runtime?
+8
java reflection extends
source share
2 answers

You cannot with reflection. But you can with CGLIB and possibly javassist

+8
source share

You can create a fake copy of A that has all the methods you want to override and compile and deploy only B.

If you do not know which methods you want to override before execution, you will need to generate the code using the compiler API, however a library such as Objectweb ASM can be much simpler. I prefer ASM because it can easily generate code to generate what you want from the template. that is, you do not need to write all the code yourself.

+3
source share

All Articles