J'utilise Javassist pour générer une classe foo
, avec la méthode bar
, mais je ne peux pas sembler trouver un moyen d'ajouter une annotation (l'annotation elle-même n » est pas t runtime généré) à la méthode. Le code que j'ai essayé ressemble à ceci:Ajout d'une annotation à une méthode générée exécution/classe à l'aide Javassist
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();
Et évidemment, je fais quelque chose de mal puisque annots
est un tableau vide.
Voici comment l'annotation ressemble à:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}