使用 Javassist 将注释添加到运行时生成的方法/类
我正在使用 Javassist 生成一个类 foo
,使用方法 bar
,但我似乎找不到向该方法添加注释(注释本身不是运行时生成的)的方法。我尝试的代码如下所示:
ClassPool pool = ClassPool.getDefault();
// create the class
CtClass cc = pool.makeClass("foo");
// create the method
CtMethod mthd = CtNewMethod.make("public Integer getInteger() { return null; }", cc);
cc.addMethod(mthd);
ClassFile ccFile = cc.getClassFile();
ConstPool constpool = ccFile.getConstPool();
// create the annotation
AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("MyAnnotation", constpool);
annot.addMemberValue("value", new IntegerMemberValue(ccFile.getConstPool(), 0));
attr.addAnnotation(annot);
ccFile.addAttribute(attr);
// generate the class
clazz = cc.toClass();
// length is zero
java.lang.annotation.Annotation[] annots = clazz.getAnnotations();
显然我做错了什么,因为 annots
是一个空数组。
注释如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}
I'm using Javassist to generate a class foo
, with method bar
, but I can't seem to find a way to add an annotation (the annotation itself isn't runtime generated) to the method. The code I tried looks like this:
ClassPool pool = ClassPool.getDefault();
// create the class
CtClass cc = pool.makeClass("foo");
// create the method
CtMethod mthd = CtNewMethod.make("public Integer getInteger() { return null; }", cc);
cc.addMethod(mthd);
ClassFile ccFile = cc.getClassFile();
ConstPool constpool = ccFile.getConstPool();
// create the annotation
AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("MyAnnotation", constpool);
annot.addMemberValue("value", new IntegerMemberValue(ccFile.getConstPool(), 0));
attr.addAnnotation(annot);
ccFile.addAttribute(attr);
// generate the class
clazz = cc.toClass();
// length is zero
java.lang.annotation.Annotation[] annots = clazz.getAnnotations();
And obviously I'm doing something wrong since annots
is an empty array.
This is how the annotation looks like:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最终解决了这个问题,我将注释添加到了错误的位置。我想将它添加到方法中,但我将它添加到类中。
固定代码如下所示:
Solved it eventually, I was adding the annotation to the wrong place. I wanted to add it to the method, but I was adding it to the class.
This is how the fixed code looks like: