views:

121

answers:

2

Hi there!

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?

+1  A: 

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.

ChssPly76
Thank you, that did the trick. I had a hard time discovering which class was the original one, I eventually got it working cutting of everything from $$$EnhancerByCGLIB$$ from the name of the class.
artemb
A: 

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.

mbenson