首页 > 解决方案 > 将对象添加到数组中

问题描述

我想创建一个代码,它使用 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);你知道将 Object 添加到数组中的正确方法是什么吗?

标签: javajavassist

解决方案


由于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")));

推荐阅读