Подтвердить что ты не робот

Добавление аннотации к созданному методу/классу среды выполнения с использованием Javassist

Я использую Javassist для создания класса foo с помощью метода bar, но я не могу показаться найти способ добавления аннотации (сама аннотация не генерируется при запуске). Код, который я пробовал, выглядит так:

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

И, очевидно, я делаю что-то неправильно, так как annots - пустой массив.

Вот как выглядит аннотация:

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

Ответ 1

В конце концов решил, что добавляю аннотацию в неправильное место. Я хотел добавить его в метод, но я добавлял его в класс.

Вот как выглядит фиксированный код:

// wrong
ccFile.addAttribute(attr);

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