23

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();
}
4

1 に答える 1

30

最終的に解決しましたが、注釈を間違った場所に追加していました。メソッドに追加したかったのですが、クラスに追加していました。

これは、修正されたコードがどのように見えるかです:

// wrong
ccFile.addAttribute(attr);

// right
mthd.getMethodInfo().addAttribute(attr);
于 2010-06-03T12:13:58.203 に答える