【问题标题】:How to print RuntimeVisibleAnnotations in java ASM如何在 java ASM 中打印 RuntimeVisibleAnnotations
【发布时间】:2015-10-26 20:20:05
【问题描述】:

我是 ASM 的新手。我有一个类文件,其中有方法的运行时可见注释。我想解析这个类文件并根据特定标准选择注释。我查看了 ASM 的文档并尝试使用 visibleAnnotation。我似乎无法打印在我的类文件中可以看到的方法注释列表。

我的代码是

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
[org.objectweb.asm.tree.AnnotationNode@5674cd4d]
MyRandomFunction2()V
[org.objectweb.asm.tree.AnnotationNode@63961c42]

我的 RandomFunction 1 和 2 有注释,但我似乎无法理解 [org.objectweb.asm.tree.AnnotationNode@5674cd4d]。

【问题讨论】:

    标签: java-bytecode-asm


    【解决方案1】:

    我自己解决了这个问题,我不得不迭代我最初没有意识到的注释。

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

    【讨论】:

    • 十多年都没有必要写这么冗长的Iterator代码了。只需写if(mn.visibleAnnotations != null) for(AnnotationNode an: mn.visibleAnnotations) System.out.println(an.values);。但我建议您实现自己的 ClassVisitor,它会在遇到时立即打印注释,而不是收集有关某个类的所有信息并遍历您感兴趣的少数几个。
    • 我最初尝试使用 for each 循环,但类型不匹配出现错误。 “无法从元素类型对象转换为注释节点”。这就是我改用迭代器的原因。
    猜你喜欢
    • 2021-09-10
    • 2015-04-06
    • 1970-01-01
    • 2016-09-09
    • 2017-11-06
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多