首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Javassist向运行时生成的方法/类添加注释

使用Javassist向运行时生成的方法/类添加注释
EN

Stack Overflow用户
提问于 2010-06-03 16:01:20
回答 1查看 16.8K关注 0票数 23

我正在使用Javassist生成一个类foo,方法是bar,但是我似乎找不到一种方法来向该方法添加批注(批注本身不是运行时生成的)。我尝试的代码如下所示:

代码语言:javascript
复制
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是一个空数组。

下面是注释的外观:

代码语言:javascript
复制
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    int value();
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2964180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档