Estoy usando Javassist para generar una clase foo
, con el método bar
, pero parece que no puedo encontrar una manera de agregar una anotación (la anotación no es t runtime generado) para el método. El código que he intentado es el siguiente:Agregando una anotación a un método/clase generados en tiempo de ejecución usando 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();
Y obviamente estoy haciendo algo mal, ya annots
es una matriz vacía.
Este es el aspecto de la anotación como:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}