开发者

Dynamically add annotation to an existing class

I have the following class

public class Person {
   ...
}

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

@SomeAnno开发者_高级运维tation
public class Person {
   ...
}

Via a simple method like so.

public static Class addAnnotation(Class originalType, Class<? extends Annotation> annotation) {
   // what goes here?
}

Is there an easy way to do this via ASM for example? What dependencies would I need. I have tried to Google this however the examples I have found are either incomplete or are doing something else. Other frameworks such as javassist would be just as good.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜