Extending class at runtime

2019-04-30 05:22发布

问题:

So for this project I am trying to extend a class at runtime. What I would like to know, is this even possible? If so, how would I do it? Are there libraries out there for these things?

回答1:

CGLib is a library you're looking for. It's quite powerfull in extending classes or implementing interfaces in runtime, so many popular frameworks, like Spring or Hibernate use it.

You can create class extension with code like

 public Object createProxy(Class targetClass) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setCallback(NoOp.INSTANCE);
    return enhancer.create();
   }

although you would probably replace NoOp callback with a useful method interceptor with desired logic.



回答2:

Yes, it is possible to extend a class at runtime. Try a library that is capable of modifying the bytecode at runtime like e.g. javassist or ASM.



回答3:

The answer depends on what you mean with "extend a class". In java "extend" means to declare another class that extends the first one (is a subclass). So if you want to create a subclass of given class, this is possible - just prepare a byte array representing the subclass and pass it to a class loader.

If you want to add fields or methods to an existing class, this is possible only at the moment when this class is being loaded, and is done by replacing the byte array representation. If class is already loaded, you cannot modify it in any way.