Pure Danger Tech


navigation
home

Package annotations

28 Feb 2007

Until recently, I was not aware that you could add annotations to packages in Java 5, or how it was done. When defining the Annotation, you of course specify it as a package annotation like so:

package puredanger.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Define an annotation that marks packages as being part of a public API.  
 * These packages might be used by a special doclet that published only 
 * API documentation, possibly in conjunction with other annotations.
 */
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.PACKAGE)
public @interface API {    
}

The @Retention above is an annotation applied to the annotation specifying that annotations should be kept in the .class files, but does not need to be loaded at runtime. The @Target annotation specifies that API should be used only with packages.

Then when you want to mark a package, where does the annotation go? Apparently it is considered to be an implementation-specific decision but file-based systems (that would be virtually all) are strongly encouraged to use a file called package-info.java in the package in question. This looks like a Java file, but cannot hold a main level class because “package-info” is an invalid Java type name. It typically contains the package definition and any annotations:

/**
 * This package contains dangerous annotations. 
 */
@API
package puredanger.annotation;
import puredanger.annotation.API;

Note that I need to import the annotation itself here that I’m using to annotate the package.

The Java Language Spec indicates that this file (if it exists) is also the preferred source of package javadoc! I tried it, and indeed the javadoc tool will pick up javadoc placed in this file above the package definition instead of a package.html file in the same package.

The JLS also notes that this file could contain package-private class definitions, although that would apparently be very bad form.