Package level annotations

While setting up JAXB2 for converting object graphs to XML I came across a not-so-nice part of the annotations specification. While looking for a way to define a package level annotation (never needed to do this before) I found the solution a bit surprising:

To define a package-level annotation one has to create a file called ‘package-info.java‘ in the root of the package and put the annotations on the package:

[java]
@XmlJavaTypeAdapter(type = AVTimePoint.class, value = AVTimePointAdapter.class)
package nl.cinema.domain.media;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
[/java]

package-info.java‘?? Grrr… since it doesn’t contain a type definition it doesn’t even pop-up in Eclipses’ source browser!

But hey… need to put them somewhere!

When the compiler encounters package-info.java file, it will create a synthetic interface, package-name.package-info. The interface is called synthetic because it is introduced by the compiler and does not have a corresponding construct in the source code. This synthetic interface makes it possible to access package-level annotations at runtime. The javadoc utility will use the package-info.java file if it is present, instead of package.html, to generate documentation…. I guess I should have known that ;) I do however still prefer the package.html convention.

This entry was posted in java. Bookmark the permalink.

2 Responses to Package level annotations

  1. tejas says:

    How did you read this package annotation at runtime?

  2. Nick Dunn says:

    I ran into this today for precisely the same reason. I had no idea you could do that. Very strange, especially since package-info.java isn’t even a valid class name.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>