向Java类添加字段 [英] Adding a field to Java class

查看:522
本文介绍了向Java类添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望在运行时使用CGLib,ASM,BCEL(方面)和Javassist将字段添加到类中。...

Looked at using CGLib, ASM, BCEL (aspect) and Javassist to add a field to a class during runtime....

只是为了直截了当看起来这些字节码操纵器不会更新实际的类,而是允许用户仅转储修改(例如使用CGLib和writeFile方法)。希望我能找到一个解决方案,可以(a)加载类(而不是使用BCEL进行InputStream),并且(b)更新类。

Just to get my head straight it looks like these bytecode manipulators don't update the actual class rather allow the user to only dump the modification (like with CGLib and the writeFile method). Was hoping I would find a solution that (a) loaded the class (rather than doing an InputStream with BCEL) and (b) updated the class.

也许这很正常?人们通常会创建一个代理并将其传递给代理吗?

Maybe this is normal? Do people usually create a proxy and pass the proxy around?

我要做的是在添加一个字段(注意:不是通过get / set方法获得的属性)之前将对象传递到寻找带有特定注释的字段(而非属性)的框架。因此,客户正在创建我想要添加额外字段的目标类。

What I want to do is to add a field (note: not a property via get/set methods) before passing the object along to a framework that looks for fields (not properties) with a particular annotation. So "clients" are creating my target classes that I want to inject with an extra field. Intercepting with AOP calls to a service layer where I want to manipulate these objects.

推荐答案

您可以使用Intrumentation重新定义类。但是,常见的限制是您无法更改使用的字段。这是因为一旦创建对象便无法更改其内容(或添加至该对象)。

You can redefine classes with Intrumentation. However a common limiation is that you cannot change the fields used. This is because you cannot change the contents of a object (or add to it) once it has been created.

在您的情况下,您可以更改

In your case you can,


  • 按照您的建议创建代理,但是代理必须是接口。

  • 创建一个具有附加字段的子类( s)

  • 在加载类之前添加字段。

这篇关于向Java类添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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