【问题标题】:Adding an annotation to a runtime generated method/class using Javassist使用 Javassist 向运行时生成的方法/类添加注释
【发布时间】:2010-06-03 08:01:20
【问题描述】:

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

【问题讨论】:

    标签: java annotations javassist


    【解决方案1】:

    最终解决了,我将注释添加到错误的位置。我想将它添加到方法中,但我正在将它添加到类中。

    这是固定代码的样子:

    // wrong
    ccFile.addAttribute(attr);
    
    // right
    mthd.getMethodInfo().addAttribute(attr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2012-07-31
      相关资源
      最近更新 更多