2010-06-03 8 views
18

kullanarak bir çalışma zamanı tarafından oluşturulan yöntem/sınıf ek açıklama ekleme foo, bar yöntemiylekullanmak için kullanıyorum, ancak ek açıklama eklemenin bir yolunu bulmak gibi görünmüyor (ek açıklama kendisi değil) t çalışma zamanı oluşturuldu).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(); 

Ve açıkçası ben annots beri yanlış bir şey yapıyorum boş dizidir: Denedim kod buna benzemez.

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface MyAnnotation { 
    int value(); 
} 

cevap

22

Yanlış yere ek açıklaması ekleyerek edildi, eninde sonunda çözüldü:

Bu açıklama benziyor nasıl. Bunu yönteme eklemek istedim, ancak bunu sınıfa ekliyordum.

// wrong 
ccFile.addAttribute(attr); 

// right 
mthd.getMethodInfo().addAttribute(attr); 
: Sabit kod neye benzediğini

budur

İlgili konular