Ich verwende Javassist, um eine Klasse foo
mit der Methode bar
zu generieren, aber ich finde keine Möglichkeit, eine Annotation hinzuzufügen (die Annotation selbst ist nicht ' t Laufzeit generiert) an die Methode. Der Code habe ich versucht, sieht wie folgt aus:Hinzufügen einer Annotation zu einer von der Laufzeit generierten Methode/Klasse mit Hilfe von 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();
Und natürlich etwas, was ich falsch mache, da annots
ist ein leeres Array.
Dies ist, wie die Anmerkung wie folgt aussieht:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}