Extending class at runtime

旧时模样 提交于 2019-12-01 05:35:32

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 e.g. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!