java - 将对象添加到数组中
问题描述
我想创建一个代码,它使用 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 添加到数组中的正确方法是什么吗?
解决方案
由于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")));
推荐阅读
- javascript - Javascript 只显示一次 div
- .net - WM_ACTIVATEAPP 消息句柄不是被激活窗口的句柄
- azure - Azure Devops Pipelines 中的工件
- c# - Linq 映射列表到
- android - 以编程方式添加的导航抽屉项目在选中时未突出显示
- swift - 如何使标签栏按钮在标签栏边界外可点击
- azure - 使用 Azure 功能在 oracle 数据库中更新记录的最大限制是多少?
- python - 如何从html运行python脚本
- python - python通过url下载zip文件-下载损坏的文件
- apache-kafka - Kafka 流式处理线程和正在处理的记录数