java 使用 Javassist 向运行时生成的方法/类添加注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2964180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding an annotation to a runtime generated method/class using Javassist
提问by Idan K
I'm using Javassistto 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:
我正在使用Javassist生成一个foo带有 method的类,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();
And obviously I'm doing something wrong since annotsis an empty array.
显然我做错了什么,因为它annots是一个空数组。
This is how the annotation looks like:
这是注释的样子:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}
回答by Idan K
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:
这是固定代码的样子:
// wrong
ccFile.addAttribute(attr);
// right
mthd.getMethodInfo().addAttribute(attr);

