The package-info.java file


Remember the javadocs are written within the class (or interface, or enum files). There are no files to document the package information (or package javadoc). This file (package-info.java) is precisely used for that. It (which must always be named as package-info.java) contains the information about the package under which it is created. 

Apart from the javadoc it also serves as a placeholder for package level annotations. Instead of say deprecating the classes one by one, the annotation could be applied to this file, and the processor deprecates the entire package. This is the place where the annotation with @Target(ElementType.PACKAGE)can be placed. In fact, the Annotation with ElementType.PACKAGE
cannot be placed on any other file, except package-info.java. The file can just contain the package name and the annotation. A sample code for package-info.java is  below. The comments can be generated as Javadocs. Also notice the import statement below the package declaration for the annotation. It was introduced in Java 5, and replaces package.html file, to make it consistent with javadoc style.


/**
 *
 * This is an annotation which can be used only at package level.
 * Note the package cannot be annotated on a class declaration but only on the file
 * package-info.java
 *
 * This package declaration is also used as an example for Target-ElementType.PACKAGE
 * example
 * Note the import statement for PackageAnnotation below the package declaration
 *
 * @author Gaurav Vishal
 *
 */
@PackageAnnotation
package in.gvbooks.annotation.pkg;
import in.gvbooks.annotation.pkg.PackageAnnotation;


The annotation file (PackageAnnotation.java) looks like this


package in.gvbooks.annotation.pkg;

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


/**
 * Refer to package-info.java file in this package and check the usage
 */
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PackageAnnotation {

}


Programmers usually ignore this file. Do not ignore them. Use them especially to create javadocs

Comments

Popular posts from this blog

Java Generics - 7. Upper and Lower Bounds

Java Functional Programming : 3. The java.util.function Library

Java Generics - 3. Multiple bounding