Dynamically add annotation to an existing class

后端 未结 1 763
暖寄归人
暖寄归人 2021-02-13 21:33

I have the following class

public class Person {
   ...
}

I would like to create another class that would look like this.

@Some         


        
相关标签:
1条回答
  • 2021-02-13 22:10

    You can use javassist project for that.

    With javassist it will be look something like that:

    ClassFile cf = ... ;
    ConstPool cp = cf.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
    
    Annotation a = new Annotation("Author", cp);
    a.addMemberValue("name", new StringMemberValue("Chiba", cp));
    attr.setAnnotation(a);
    cf.addAttribute(attr);
    cf.setVersionToJava5();
    

    Hope it helps. Alexey

    0 讨论(0)
提交回复
热议问题