2015-10-26 96 views
0

我是ASM的新手。我有一個類文件,其中有方法的運行時可見註釋。我想解析這個類文件並根據特定的標準選擇註釋。我查看了ASM的文檔,並嘗試使用visibleAnnotation。我似乎無法打印我可以在我的課堂文件中看到的方法註釋列表。如何在java ASM中打印RuntimeVisibleAnnotations

我的代碼

import java.io.FileInputStream; 
import java.io.InputStream; 
import java.util.Iterator; 

import org.objectweb.asm.tree.AnnotationNode; 
import org.objectweb.asm.tree.ClassNode; 
import org.objectweb.asm.tree.MethodNode; 
import org.objectweb.asm.ClassReader; 

public class ByteCodeParser { 

    public static void main(String[] args) throws Exception{ 
     InputStream in=new FileInputStream("sample.class"); 

     ClassReader cr=new ClassReader(in); 
     ClassNode classNode=new ClassNode(); 

     //ClassNode is a ClassVisitor 
     cr.accept(classNode, 0); 

     // 
     Iterator<MethodNode> i = classNode.methods.iterator(); 
     while(i.hasNext()){ 
      MethodNode mn = i.next(); 

      System.out.println(mn.name+ "" + mn.desc); 
      System.out.println(mn.visibleAnnotations); 

     } 

    } 

} 

的輸出是:

<clinit>()V 
null 
<init>()V 
null 
MyRandomFunction1()V 
[[email protected]] 
MyRandomFunction2()V 
[[email protected]] 

我RandomFunction 1 & 2具有註釋,但我似乎無法瞭解[org.objectweb.asm.tree。 AnnotationNode @ 5674cd4d。

回答

0

我自己解決了這個問題,我不得不迭代我沒有意識到的註釋。

if (mn.visibleAnnotations != null) { 
      Iterator<AnnotationNode>j=mn.visibleAnnotations.iterator(); 
      while (j.hasNext()) { 
       AnnotationNode an=j.next(); 
       System.out.println(an.values); 

      } 
} 
+1

現在沒有必要編寫如此冗長的'Iterator'代碼超過十年了。只要爲(AnnotationNode an:mn.visibleAnnotations)System.out.println(an.values);'寫入if(mn.visibleAnnotations!= null);'。但我建議實現你自己的'ClassVisitor',它在遇到時正確地打印註釋,而不是收集關於某個類的所有信息,並遍歷你感興趣的幾個。 – Holger

+0

我試着用最初的每個循環,但出現錯誤類型不匹配。 「無法從元素類型對象轉換爲註釋節點」。這就是爲什麼我使用迭代器。 – user225008