我正在使用 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();
}
最佳答案
最终解决了,我将注释添加到错误的位置。我想将它添加到方法中,但我正在将它添加到类中。
这是固定代码的样子:
// wrong
ccFile.addAttribute(attr);
// right
mthd.getMethodInfo().addAttribute(attr);
关于java - 使用 Javassist 向运行时生成的方法/类添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2964180/