使用Javassist向类添加注释

时间:2018-05-31 09:53:56

标签: java reflection annotations javassist

我正在尝试使用javassist

动态地向类添加注释

我的代码如下

Class annotatedClass = addFrequencyAnnotation(MyClass.class.getSimpleName(),
          MyAnnotation.class.getSimpleName(), 10);

annotatedClass.isAnnotationPresent(MyAnnotation.class); // Returns false

但是返回的类没有添加注释。

TextView[] containers=new TextView[2];

我不确定我的代码中缺少什么。有人可以帮助确定问题吗?

1 个答案:

答案 0 :(得分:1)

您应该使用MyAnnotation.class.getName而不是MyAnnotation.class.getSimpleName。因为MyAnnotation但没有yourpackage.MyAnnotation

  public static void main(String[] args) throws Exception {
    Class<?> annotatedClass = addAnnotation(MyClass.class.getName(), MyAnnotation.class.getName(), 10);

    System.out.println(annotatedClass.getAnnotation(MyAnnotation.class));
  }

  private static Class<?> addAnnotation(String className, String annotationName, int frequency) throws Exception {
    ClassPool pool = ClassPool.getDefault();
    CtClass ctClass = pool.makeClass(className + "1");//because MyClass has been defined

    ClassFile classFile = ctClass.getClassFile();
    ConstPool constpool = classFile.getConstPool();

    AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
    Annotation annotation = new Annotation(annotationName, constpool);
    annotation.addMemberValue("frequency", new IntegerMemberValue(classFile.getConstPool(), frequency));
    annotationsAttribute.setAnnotation(annotation);

    ctClass.getClassFile().addAttribute(annotationsAttribute);
    return ctClass.toClass();
  }