如何使用 cglib 双重增强一个类?
这是代码:
Patient patient = factory.createPatient();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(patient.getClass());
enhancer.setCallback(new DefaultMethodInterceptor(patient));
patient = (Patient) enhancer.create();
assertThat(patient.getFirstName()).isNotNull();
Enhancer enhancer2 = new Enhancer();
enhancer2.setSuperclass(patient.getClass());
enhancer2.setCallback(new DefaultMethodInterceptor(patient));
patient = (Patient) enhancer2.create();
assertThat(patient.getFirstName()).isNotNull();
它在最后一个断言上失败,
net.sf.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
...
Caused by: java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.ClassFormatError: Duplicate method name&signature in class file my/package/entity/Patient$$EnhancerByCGLIB$$ca1e6685$$EnhancerByCGLIB$$f52743be
因为我想增强 Hibernate 的实体,但有时它会自行返回已经增强的实体,而我的第二次增强会失败。 我怎样才能避免这种情况?
Here's the code:
Patient patient = factory.createPatient();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(patient.getClass());
enhancer.setCallback(new DefaultMethodInterceptor(patient));
patient = (Patient) enhancer.create();
assertThat(patient.getFirstName()).isNotNull();
Enhancer enhancer2 = new Enhancer();
enhancer2.setSuperclass(patient.getClass());
enhancer2.setCallback(new DefaultMethodInterceptor(patient));
patient = (Patient) enhancer2.create();
assertThat(patient.getFirstName()).isNotNull();
It fails on the last assert with
net.sf.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
...
Caused by: java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.ClassFormatError: Duplicate method name&signature in class file my/package/entity/Patient$EnhancerByCGLIB$ca1e6685$EnhancerByCGLIB$f52743be
I ask this because I want to enhance Hibernate's entities, but sometimes it returns already enhanced ones by itself and my second enhancement fails. How can I avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要通过
Enhancer.isEnhanced()
方法检查您的类是否已被增强。如果是,您的第二个增强应该应用于原始类,而不是像上面代码中那样应用于已经增强的版本。 您仍然可以在
MethodInterceptor.intercept()
实现中复合增强功能,但必须小心行事。You need to check whether your class is already enhanced via
Enhancer.isEnhanced()
method.If it is, your 2nd enhancement should be applied to original class, not the already enhanced version like you do in the above code. You can still compound your enhancements within
MethodInterceptor.intercept()
implementation but you have to do that with care.这对我来说也很有帮助。 只是想指出,在链上调用 getSuperclass() 并检查每个的Enhancer.isEnhanced() 应该找到正确的超类。
This was quite helpful to me, as well. Just wanted to point out that calling getSuperclass() up the chain and checking Enhancer.isEnhanced() for each should locate the proper superclass.