我正在使用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();
}
发布于 2010-06-03 20:13:58
最终解决了这个问题,我将注释添加到了错误的位置。我想将它添加到方法中,但我正在将它添加到类中。
修复后的代码如下所示:
// wrong
ccFile.addAttribute(attr);
// right
mthd.getMethodInfo().addAttribute(attr);
https://stackoverflow.com/questions/2964180
复制相似问题