javaannotationsbcel

Read annotations using Apache Bcel library


I'm trying to read class annotations using this code:

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

But for this code attribute instanceof Annotations I get error: Inconvertible types; cannot cast 'com.sun.org.apache.bcel.internal.classfile.Attribute' to 'org.apache.bcel.classfile.Annotations'

Do you know how I can solve this issue?


Solution

  • This works for me. You didn't give a complete compilable example nor say what commands you ran. Here is what I did.

    File Hello.java:

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

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

    Commands to run:

    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
    

    All the commands complete without errors.