CGLib - 创建一个带有一些字段的 bean 并在其上放置注释?

use*_*211 1 java annotations cglib

是否可以生成一个 bean 类,其中的字段用指定的注释进行注释?我知道可以创建 bean,但是注释呢...?我找不到任何关于它的信息,所以我对此有强烈的怀疑,唯一确定的方法就是在这里询问......

// 我发现了一些可能有用的东西...请验证此代码。它使用 javassist 功能。

    // pool creation
    ClassPool pool = ClassPool.getDefault();
    // extracting the class
    CtClass cc = pool.getCtClass(clazz.getName());
    // looking for the method to apply the annotation on
    CtField fieldDescriptor = cc.getDeclaredField(fieldName);
    // create the annotation
    ClassFile ccFile = cc.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constpool,
            AnnotationsAttribute.visibleTag);

    Annotation annot = new Annotation("sample.PersonneName", constpool);
    annot.addMemberValue("name",
            new StringMemberValue("World!! (dynamic annotation)", ccFile.getConstPool()));
    attr.addAnnotation(annot);

    // add the annotation to the method descriptor
    fieldDescriptor.getFieldInfo().addAttribute(attr);
Run Code Online (Sandbox Code Playgroud)

它的问题是我不知道如何在新创建的类型上应用现有注释......有没有办法做到这一点?

Raf*_*ter 5

最简洁的答案是不。Cglib 本身不支持此类功能。Cglib 相当古老,其核心是在 Java 中引入注释之前编写的。从此以后,cglib 就不再被维护太多了。

但是,您可以将 ASM(cglib 所基于的工具)偷运ClassVisitorEnhancer并手动添加注释。不过,我建议您直接使用 ASM 构建您的 bean。对于一个简单的 POJO bean 来说这并不是一项艰巨的任务,ASM 是一个很棒的、维护良好、文档齐全的工具。Cglib 不是。

更新:您可能想看看我的库Byte Buddy,它能够满足您的要求。以下代码将创建一个具有可见性类型的Object公共字段的子类。该字段被注释为fooStringpublic

@Retention(RetentionType.RUNTIME)
@interface MyAnnotation { }

class MyAnnotationImpl implements MyAnnotation {
  @Override
  public Class<? extends Annotation> annotationType() {
    return MyAnnotation.class;
  }
}

new ByteBuddy()
  .subclass(Object.class)
  .defineField("foo", String.class, MemberVisibility.PUBLIC)
  .annotateField(new MyAnnotationImpl())
  .make()
  .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
  .getLoaded()
  .newInstance();
Run Code Online (Sandbox Code Playgroud)