简体   繁体   English

在运行时扩展类

[英]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. CGLib是您要查找的库。 It's quite powerfull in extending classes or implementing interfaces in runtime, so many popular frameworks, like Spring or Hibernate use it. 它在运行时扩展类或实现接口方面非常强大,因此许多流行的框架(如Spring或Hibernate)都使用它。

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. 尽管您可能会使用具有所需逻辑的有用的方法拦截器替换NoOp回调。

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 . 尝试一个能够在运行时修改字节码的库,例如javassistASM

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). 在Java中,“ extend”意味着声明另一个扩展第一个类的类(是子类)。 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. 如果已经加载了类,则无法以任何方式对其进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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