我正在尝试使用以下代码读取类注释:
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'
你知道我怎么解决这个问题吗?
发布于 2020-04-16 23:05:58
这对我很有效。你没有给出一个完整的可编译的例子,也没有说你运行了什么命令。这就是我所做的。
文件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所有命令都已完成,并且没有错误。
https://stackoverflow.com/questions/61245667
复制相似问题