首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Apache Bcel库读取注释

使用Apache Bcel库读取注释
EN

Stack Overflow用户
提问于 2020-04-16 16:18:45
回答 1查看 98关注 0票数 0

我正在尝试使用以下代码读取类注释:

代码语言:javascript
复制
JavaClass jclas = new ClassParser("src\\test\\org\\poc\\TargetHello.class").parse();

        ClassGen cg = new ClassGen(jclas);

        Attribute[] attributes = cg.getAttributes();

        for (Attribute attribute : attributes) {
            if (attribute instanceof Annotations) {
                Annotations annotations = (Annotations) attribute;
                AnnotationEntry[] entries= annotations.getAnnotationEntries();
            }
        }

但是对于这个代码attribute instanceof Annotations,我得到了错误:Inconvertible types; cannot cast 'com.sun.org.apache.bcel.internal.classfile.Attribute' to 'org.apache.bcel.classfile.Annotations'

你知道我怎么解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-16 23:05:58

这对我很有效。你没有给出一个完整的可编译的例子,也没有说你运行了什么命令。这就是我所做的。

文件Hello.java

代码语言:javascript
复制
@Deprecated
public class Hello {
  public static void main(String[] args) {}
}

文件AttributeAnnotations.java

代码语言:javascript
复制
import java.io.IOException;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Annotations;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.ClassGen;

public class AttributeAnnotations {

  public static void main(String[] args) throws IOException {

    JavaClass jclas = new ClassParser("Hello.class").parse();

    ClassGen cg = new ClassGen(jclas);

    Attribute[] attributes = cg.getAttributes();

    for (Attribute attribute : attributes) {
      System.out.println("attribute: " + attribute);
      if (attribute instanceof Annotations) {
        Annotations annotations = (Annotations) attribute;
        System.out.println("annotations: " + annotations);
        AnnotationEntry[] entries = annotations.getAnnotationEntries();
      }
    }
  }
}

要运行的命令:

代码语言:javascript
复制
wget https://repo1.maven.org/maven2/org/apache/bcel/bcel/6.4.1/bcel-6.4.1.jar
javac Hello.java
javac -cp bcel-6.4.1.jar AttributeAnnotations.java
java -cp .:bcel-6.4.1.jar AttributeAnnotations

所有命令都已完成,并且没有错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61245667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档