Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extend a class at runtime with reflection

Imagine that I have two Class A and B, B extends A, like

class B extends A
{
  ....
}

However, in my case, Class A is encrypted and can be only loaded by my ClassLoader at runtime (at compiling time, A.class can not be recognized as a .class file because it is encrypted). This means Class A doesn't exist at compiling time.

My questions are:

  1. how can write the code for Class B, as some methods override the methods in Class A?
  2. how can I specify Class B extends to Class A at runtime?
like image 347
user733172 Avatar asked May 01 '11 10:05

user733172


2 Answers

You can't with reflection. But you can with CGLIB and perhaps javassist

like image 65
Bozho Avatar answered Sep 27 '22 21:09

Bozho


You can create a dummy copy of A which has all the methods you want to override and compile and deploy just B.

If you don't know what methods you want to override until runtime, you will need to generate code using either the Compiler API, however a library like Objectweb's ASM is likely to be much simpler. I prefer ASM because it can easily generate code to generate what you want from a template. i.e. you don't have to write all the code yourself.

like image 41
Peter Lawrey Avatar answered Sep 27 '22 20:09

Peter Lawrey