动态添加注释到现有类
问题描述:
我有下面的类动态添加注释到现有类
public class Person {
...
}
我想创建另一个类,是这样的。
@SomeAnnotation
public class Person {
...
}
通过像这样的简单方法。
public static Class addAnnotation(Class originalType, Class<? extends Annotation> annotation) {
// what goes here?
}
有没有一种简单的方法来通过ASM做到这一点,例如?我需要什么样的依赖关系。我试图谷歌这个,但我发现的例子不完整或正在做其他事情。其他的框架,比如javassist,会一样好。
答
您可以使用javassist项目。
用Javassist将寻找类似的东西:
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();
希望它能帮助。 Alexey