2015-09-07 40 views
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"); 
    } 

回答

0

当您使用附加注释创建新类时,永远不会替换实际加载的原始类文件。

因此,您的Foo类将以其原始版本加载,或者已经加载,因此您的更改是无效的。

+0

嗯,但我将如何“替换原来的实际加载的类文件”?我认为这是ClassWriter所做的。 – KIC

+1

不,它只是生成一个表示修改后的类的字节数组。 –