使用 Javassist 向运行时生成的方法/类添加注释 [英] Adding an annotation to a runtime generated method/class using Javassist
本文介绍了使用 Javassist 向运行时生成的方法/类添加注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Javassist 生成一个类 foo
,使用方法 bar
,但我似乎找不到向方法添加注释(注释本身不是运行时生成的)的方法.我试过的代码是这样的:
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();
显然我做错了什么,因为 annots
是一个空数组.
And obviously I'm doing something wrong since annots
is an empty array.
这是注释的样子:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}
推荐答案
最终解决了,我在错误的地方添加了注释.我想将它添加到方法中,但我将它添加到类中.
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.
这是固定代码的样子:
// wrong
ccFile.addAttribute(attr);
// right
mthd.getMethodInfo().addAttribute(attr);
这篇关于使用 Javassist 向运行时生成的方法/类添加注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文