1 Reply Latest reply on Jul 4, 2009 10:02 PM by paulkeeble

    Adding annotations to methods

    paulkeeble

      I want to put my own annotation on a CtMethod. I can only see a getAnnotations method, and equally I can't find a setMethodInfo (which I think could potentially work with AnnotationsWriter).

      How do you add an annotation?

        • 1. Re: Adding annotations to methods
          paulkeeble

          In the end I managed to work it out and answer my own question. The key was understanding that you need to add the AnnotationsAttribute instance to the Info of the method.

          That is the rough solution is:

          CtClass clazz = ....
          ClassFile classFile = clazz.getClassFile();
          ConstPool cp = classFile.getConstPool();
          AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
          
          Annotation useAnnotation = new Annotation("org.package.AnnotationType",cp);
          annotation.addMemberValue("name", new StringMemberValue("Paul",cp));
          
          attr.setAnnotation(useAnnotation);
          
          m.getMethodInfo().addAttribute(attr);
          
          


          So the only real difference between the CtClass, CtMethod and even parameters is I needed to do the appropriate getXXXInfo and then add the attribute directly.