Retain annotations on CGLIB proxies?

后端 未结 4 1272
抹茶落季
抹茶落季 2020-12-06 00:44

Am trying to create an object using an AOP framework which uses CGLIB to create proxy objects. Strangely enough, the \"enhanced\" proxy object is devoid of ANY annotations t

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 01:04

    Cglib is not capable of retaining annotations without changing its internal implementation. This is however quite complicated and believe me I tried. My altered version I finally came up with was however so complicated that I decided to rather implement Byte Buddy, another code generation library which is capable of such functionality.

    Here is an example of how you can create subclass that

    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation { }
    
    @MyAnnotation
    class MyClass { }
    
    assertThat(new ByteBuddy()
      .subclass(Object.class)
      .attribute(TypeAttributeAppender.ForSuperType.INSTANCE)
      .make()
      .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded()
      .isAnnotationPresent(MyAnnotation.class), is(true));
    

    Byte Buddy comes with an extensive full-text documentation and javadoc and it is quite extensible. Hope you make good use of the library.

提交回复
热议问题