gpt4 book ai didi

java - 使用 Apache Bcel 库读取注释

转载 作者:行者123 更新时间:2023-12-02 08:43:15 25 4
gpt4 key购买 nike

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

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;无法将“com.sun.org.apache.bcel.internal.classfile.Attribute”转换为“org.apache.bcel.classfile.Annotations”

你知道我该如何解决这个问题吗?

最佳答案

这对我有用。您没有给出完整的可编译示例,也没有说明您运行了哪些命令。这就是我所做的。

文件Hello.java:

@Deprecated
public class Hello {
public static void main(String[] args) {}
}

文件AttributeAnnotations.java:

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();
}
}
}
}

要运行的命令:

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

所有命令均已完成且没有错误。

关于java - 使用 Apache Bcel 库读取注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61245667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com