本文介绍了动态地向现有类添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程
public class Person {
...
}
我想创建另一个看起来像这样的类。
I would like to create another class that would look like this.
@SomeAnnotation
public class Person {
...
}
通过类似的简单方法。
public static Class addAnnotation(Class originalType, Class<? extends Annotation> annotation) {
// what goes here?
}
例如,通过ASM有一种简单的方法吗?我需要什么依赖项。我试过谷歌这个但是我发现的例子要么不完整要么正在做其他事情。其他框架如javassist也同样好。
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.
推荐答案
你可以使用项目。
使用javassist它将看起来像这样:
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();
希望有所帮助。
Alexey
Hope it helps.Alexey
这篇关于动态地向现有类添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!