-1

I want to create a code which uses Javassist to add annotations into compiled Java classes. I tried this:

        ClassFile classFile = ClassPool.getDefault().get("org.poc.Hello").getClassFile();
        ConstPool constPool = classFile.getConstPool();
        AnnotationsAttribute attr= new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        Annotation annotation = new Annotation("Author", constPool);
        Annotation author = new Annotation("Description", constPool);
        Annotation[] array = new Annotation[4];
        array[0] = annotation;
        array[1] = author;

        attr.setAnnotations(array);
        classFile.addAttribute(attr);
        classFile.write(new DataOutputStream(new FileOutputStream("src/test/org/poc/Foo.class")));

But when I run it I get NPE at this line: attr.setAnnotations(array); do you know what is the proper way to add Object into array?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

0

you are getting null pointer exception because of new Annotation[4];. You have only 2 annotations. so remaining 2 will be null.

        ClassFile classFile = ClassPool.getDefault().get("org.poc.Hello").getClassFile();
        ConstPool constPool = classFile.getConstPool();
        AnnotationsAttribute attr= new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        Annotation annotation = new Annotation("Author", constPool);
        Annotation author = new Annotation("Description", constPool);
        Annotation[] array = new Annotation[2];
        array[0] = annotation;
        array[1] = author;

        attr.setAnnotations(array);
        classFile.addAttribute(attr);
        classFile.write(new DataOutputStream(new FileOutputStream("src/test/org/poc/Foo.class")));
Binu
  • 754
  • 6
  • 15