2 Replies Latest reply on Aug 13, 2008 2:42 PM by theyurinator

    Help on class anotation

    theyurinator

      Hello,

      I am new to Javassist, so excuse me for all the things I do not know yet.

      I am having trouble adding a class annotation. I do exactly what the AnnotationsAttribute API page sample does:

      ClassFile cf = ... ;
      ConstPool cp = cf.getConstPool();
      AnnotationsAttribute attr
      = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
      Annotation a = new Annotation("Author", cp);
      a.addMemberValue("name", new StringMemberValue("Chiba", cp));
      attr.setAnnotation(a);
      cf.addAttribute(attr);
      cf.setVersionToJava5();

      But when I create this page, using ct.write(), I just get a class which extends an Object with an empty constructor, but no annotation.

      Any insight?

      Thank you.

        • 1. Re: Help on class anotation
          theyurinator

          To be a little more specific, this is the exact code I have

          public static void main(String[] args) {
           ClassPool pool = ClassPool.getDefault();
           CtClass cc = pool.makeClass("sample");
           ClassFile cf = cc.getClassFile();
           ConstPool cp = cf.getConstPool();
          
           AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
           Annotation a = new Annotation("Author", cp);
           a.addMemberValue("name", new StringMemberValue("Chiba", cp));
           attr.setAnnotation(a);
           cf.addAttribute(attr);
           cf.setVersionToJava5();
          
           try {
           cc.writeFile();
           } catch (NotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           } catch (CannotCompileException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           }
           }


          and this is what I see with javap as a result.

          public class sample extends java.lang.Object{
           public sample();
          }
          


          I don't really understand what I am doing wrong? If I step through with the debugger, I do see the AnnotationsAttribute added to the ClassFile object, and the Annotation object is added to the AnnotationsAttribute object.

          • 2. Re: Help on class anotation
            theyurinator

            Please ignore this topic, I have realized that javap does not printout annotations unless I put the -verbose flag on.