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
不,它只是生成一个表示修改后的类的字节数组。 –