Skip to main content

Should Class.getAnnotations fail if an annotation type is not available?

Posted by ss141213 on October 8, 2009 at 11:26 PM PDT

While evaluating a GlassFish bug, I discovered a discrepancy in behavior of Class.getAnnotations() between IBM JRE and Sun JRE. the complex GlassFish issue boiled down to a simple test case as discussed below. The question is what should be the behavior of Class.getAnnotations() if one or more annotation class is not available at runtime. Consider the following test case:

// Main.java

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface Bar {}

@Bar
class Foo {}

class Main {
public static void main(String[] args) throws Exception{
  Annotation[] as = Foo.class.getAnnotations();
  System.out.println("Found " + as.length + " no. of annotations");
}
}

When you compile this, you shall obviously get Main.class, Foo.class and Bar.class. Remove Bar.class and run:

java Main

On IBM JRE (I am using 1.6.0 SR5 on AIX platform), it results in

Exception in thread "main" java.lang.TypeNotPresentException: Type Bar not present
        at com.ibm.oti.reflect.AnnotationHelper.getAnnotation(AnnotationHelper.java:38)
        at com.ibm.oti.reflect.AnnotationHelper.getDeclaredAnnotations(AnnotationHelper.java:50)
        at java.lang.Class.getDeclaredAnnotations(Class.java:1628)
        at java.lang.Class.getAnnotations(Class.java:1589)
        at Main.main(Main.java:13)
Caused by: java.lang.ClassNotFoundException: Bar
        at java.lang.Class.forName(Class.java:169)
        at com.ibm.oti.reflect.AnnotationHelper.getAnnotation(AnnotationHelper.java:33)
        ... 4 more

where as while using Sun JRE (1.6.0_07), the program prints:

Found 0 no. of annotations

Conclusion:

I believe it is a bug in IBM JRE. There used to be a similar bug in Sun JDK. See http://bugs.sun.com/view_bug.do?bug_id=6322301 for details. It says that Class.getAnnotations() is supposed to ignore when a annotation type can't be loaded. Sun JDK has been fixed. Now time for IBM JDK to be fixed.

Related Topics >>

Comments

already fixed.

Sahoo, if you see the sun jdk bug, you will see it was fixed in 5.0u6 and you tried SR5 for IBM JRE...see the disconnect? Yes, it's already fixed in 1.5 SR6b :) -- dims

What's the connection betn IBM JDK 1.6.0 SR5 and Sun JDK 5.0_u6?

dims:
It is good to know that it has been fixed in IBM JDK, but I don't see the connection you made. What's the relation between Sun JDK 5.0_u6 and IBM JDK 1.6.0 SR5? One if Java 1.5 and the other one is Java 1.6 implementation. The bug was fixed in Sun JDK some 3 years ago. When did IBM JDK 1.6.0 SR5 come out? Can't be 3 years back, can it?

Sahoo