我正在尝试使用javassist动态向类添加注释

我的代码如下

private Class addAnnotation(String className,String annotationName, int frequency) throws Exception{
    ClassPool pool = ClassPool.getDefault();
    CtClass ctClass = pool.makeClass(className);

    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();
  }


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

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

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


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

最佳答案

您应该使用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();
  }

关于java - 使用Javassist向类添加注释,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50621480/

10-12 16:36