title: Adding an annotation to a runtime generated method/class using Javassist
body: <p>I'm using <a href="http://www.csg.is.titech.ac.jp/~chiba/javassist/" rel="noreferrer">Javassist</a> to generate a class <code>foo</code>, with method <code>bar</code>, but I can't seem to find a way to add an annotation (the annotation itself isn't runtime generated) to the method. The code I tried looks like this:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>And obviously I'm doing something wrong since <code>annots</code> is an empty array.</p>
  
  <p>This is how the annotation looks like:</p>
  
  <pre><code>@Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  public @interface MyAnnotation {
      int value();
  }
  </code></pre>