我正在尝试使用以下代码读取类注释:
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'
您知道我该如何解决吗?
最佳答案
这对我有用。您没有给出完整的可编译示例,也没有说出您运行的命令。这是我所做的。
文件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/