代码之家  ›  专栏  ›  技术社区  ›  Idan K

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

  •  20
  • Idan K  · 技术社区  · 14 年前

    我在用 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();
    }
    
    1 回复  |  直到 6 年前
        1
  •  24
  •   Idan K    14 年前

    最终解决了这个问题,我把注释添加到了错误的地方。我想将它添加到方法中,但我正在将它添加到类中。

    固定代码如下所示:

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