Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

And obviously I'm doing something wrong since annots is an empty array.

This is how the annotation looks like:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    int value();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

This is how the fixed code looks like:

// wrong
ccFile.addAttribute(attr);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...