how to extend a class at runtime with reflection
Asked Answered
C

2

8

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?
Chopper answered 1/5, 2011 at 10:7 Comment(0)
L
8

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

Lob answered 1/5, 2011 at 10:9 Comment(0)
M
3

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.

Moonrise answered 1/5, 2011 at 11:13 Comment(5)
Hi, I think "You can create a dummy copy of A which has all the methods you want to override and compile and deploy just B." is a easy&right way. But there is a question not clear. We say, we have Class A, and I create a dummy copy, Class dummy_A, at compiling time so as to deploy Class B. Then at runtime, how to replace the content of Class dummy_A with the content of Class A. I feel this is like although we create a class at compiling time, but it is just a shell. Then at runtime, we change the class dynamically. How to do the change? Thanks.Chopper
No, you create a class called "A" in the same package. It has the same name and package and methods as the class you want to extend. When you deploy the code, you only deploy B (don't deploy the dummy "A") Your class loader will load the real A and your B. As long as the methods etc. you use are the same, it will all work.Moonrise
Hi Peter, I see... Well, this is a brilliantChopper
Hi Peter, I see... Well, this is a brilliant way. Thanks for your kindly help. One further question. My real situation is that the I need to create a jar file including Class A firstly as a third-party component. Then I develop Class B (extends Class A) as open source. Your way is based on the deployment of .class files. But in my real situation, the Class B can not extend Class A (in a separated JAR library) because Class A is encrypted. This is why a wrapper of Class A is necessary. I do this is to protect the Class A code. Any idea? Thanks for your further help and suggestion.Chopper
A may be encrypted, but it has to be decrypted to be used. This means at runtime it is just like any other class, so I don't see the problem.Moonrise

© 2022 - 2024 — McMap. All rights reserved.