How can I double a class using cglib?

Here is 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 does not work on the last statement 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 about this because I want to improve Hibernate objects, but sometimes it returns already extended ones by itself, and my second improvement fails. How can i avoid this?

+3
source share
2 answers

You need to check if your class is improved using the method Enhancer.isEnhanced().

If so, your second promotion should apply to the original class, and not to an already improved version, as in the code above. You can still combine your improvements within the implementation MethodInterceptor.intercept(), but you should do this with caution.

+6
source

. , getSuperclass() Enhancer.isEnhanced() .

+2

Source: https://habr.com/ru/post/1715172/


All Articles