简体   繁体   中英

Extending class at runtime

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM