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

    Adding annotations to methods

    Paul Keeble Newbie

      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
          Paul Keeble Newbie

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

          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.