Week 102 — What is the `package-info.java` file and what can be done with it?

Question of the Week #102
What is the package-info.java file and what can be done with it?
2 Replies
CrimsonDragon1
CrimsonDragon12mo ago
The package-info.java can be used to provide Javadoc documentation for a package. After creating a package-info.java file in some package, one would typically add a Javadoc comment followed by a package declaration stating the package the file is located in.
/**
* This is my package.
+ It can do a lot of stuff.
* Obviously, this should be a proper documentation instead of this sample text.
*/
package com.example.mypackage;
/**
* This is my package.
+ It can do a lot of stuff.
* Obviously, this should be a proper documentation instead of this sample text.
*/
package com.example.mypackage;
The javadoc tool will recognize this file and include the Javadoc comment in the generated documentation.
CrimsonDragon1
CrimsonDragon12mo ago
This file can also be used to add annotations to a package. For example, assume an annotation com.example.annotations.MyAnnotation with the PACKAGE target:
package com.example.annotations;

import java.lang.annotation.*;

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PACKAGE)
public @interface MyAnnotation{

}
package com.example.annotations;

import java.lang.annotation.*;

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PACKAGE)
public @interface MyAnnotation{

}
This annotation can be used in a package-info.java file before the package declaration. Annotations in the package-info.java can be imported after the package declaration:
@MyAnnotation
package com.example.mypackage;

import com.example.annotations.MyAnnotation;
@MyAnnotation
package com.example.mypackage;

import com.example.annotations.MyAnnotation;
Annotations like these are considered to annotate the package. An example of this is the @NullMarked annotation in jspecify that can be applied on packages and modules among other elements.
@NullMarked
package com.example.mypackage;

import org.jspecify.NullMarked;
@NullMarked
package com.example.mypackage;

import org.jspecify.NullMarked;
📖 Sample answer from dan1st

Did you find this page helpful?