我在用
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();
}