我想创建一个使用Javassist将注释添加到已编译Java类中的代码。我试过了:
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")));
但是当我运行它时,我在这一行得到了NPE:attr.setAnnotations(array);
您知道将对象添加到数组中的正确方法是什么吗?
由于new Annotation[4];
,您将获得空指针异常。您只有2个注释。因此剩余的2将为空。
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")));