Why doesn’t a missing annotation cause a ClassNotFoundException at runtime?

In the earlier public drafts for JSR-175 (annotations), it was discussed if the compiler and runtime should ignore unknown annotations, to provide a looser coupling between the usage and declaration of annotations. A specific example was the use of applications server specific annotations on an EJB to control the deployment configuration. If the same bean should be deployed on a different application server, it would have been convenient if the runtime simply ignored the unknown annotations instead of raising a NoClassDefFoundError.

Even if the wording is a little bit vague, I assume that the behaviour you are seeing is specified in JLS 13.5.7: “… removing annotations has no effect on the correct linkage of the binary representations of programs in the Java programming language.” I interpret this as if annotations are removed (not available at runtime), the program should still link and run and that this implies that the unknown annotations are simply ignored when accessed through reflection.

The first release of Sun’s JDK 5 did not implement this correctly, but it was fixed in 1.5.0_06. You can find the relevant bug 6322301 in the bug database, but it does not point to any specifications except claiming that “according to the JSR-175 spec lead, unknown annotations must be ignored by getAnnotations”.

Leave a Comment