在运行时扩展类 [英] Extending class at runtime

查看:160
本文介绍了在运行时扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于这个项目,我试图在运行时扩展一个类。
我想知道的是,这甚至可能吗?如果是这样,我该怎么做?那些东西都有库吗?

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 是您正在寻找的库。它在扩展类或在运行时实现接口方面非常强大,因此许多流行的框架(如Spring或Hibernate)都使用它。

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();
   }

虽然您可能会替换 NoOp 使用有用的方法拦截器回调所需的逻辑。

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

这篇关于在运行时扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆