开发者

how to extend a class at runtime with reflection

开发者 https://www.devze.com 2023-03-02 02:30 出处:网络
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,

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:开发者_Python百科

  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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消