2
我想使用ASM字節碼操作將註釋添加到外部類,但似乎我缺少一些東西。打印結果仍然沒有任何註釋。使用ASM向外部類添加註釋
private void fixAnnotations4Classes() throws Exception {
final ClassReader reader = new ClassReader("some/3rdparty/class/Foo");
final ClassNode classNode = new ClassNode();
reader.accept(classNode, 0);
List<FieldNode> fields = classNode.fields;
List<AnnotationNode> visibleAnnotations = fields.get(0).visibleAnnotations;
visibleAnnotations.add(new AnnotationNode("my/new/Annotation"));
ClassWriter writer = new ClassWriter(0);
classNode.accept(writer);
System.out.println(Arrays.toString(Foo.class.getDeclaredField("profile").getAnnotations()));
System.out.println("FIN");
}
嗯,但我將如何「替換原來的實際加載的類文件」?我認爲這是ClassWriter所做的。 – KIC
不,它只是生成一個表示修改後的類的字節數組。 –