package-info.java是一个Java文件,可以放到任意Java源码包执行。不过里面的内容有特定的要求,其主要目的是为了提供包级别相关的操作,比如包级别的注解、注释及公共变量。
用途
一、提供包级别的注解
介绍
在对应的源码包提供包级别的注解
样例
- 创建包注解
@Target(ElementType.PACKAGE) @Retention(RetentionPolicy.RUNTIME) public @interface TestPkg { }
- 在package-info.java添加注解
@TestPkg package com.exercise.data_collection_error_info_transformation.component;
- 查看对应的包的注解
public class Client { public static void main(String[] args) throws ClassNotFoundException { // 查看包注解 String pkgName = "com.exercise.data_collection_error_info_transformation.component"; Package pkg = Package.getPackage(pkgName); Annotation[] annotations = pkg.getAnnotations(); for(Annotation an:annotations){ if(an instanceof TestPkg){ System.out.println("Hi,I'm the TestPkg"); } } // 查看包下面对应的类的注解 Class test = Class.forName("com.exercise.data_collection_error_info_transformation.component.Test"); Annotation[] annotations2 = test.getAnnotations(); for(Annotation an:annotations2){ if(an instanceof TestPkg){ System.out.println("Hi,I'm the Class TestPkg"); } } } }
结果如下,只输出对应的包的注解,包内部的类是没有该注解的。
Hi,I'm the TestPkg
- Deprecated注解的使用
如果一整个包都是过时的话,可以直接在package-info.java下面,添加注解@Deprecated,表示该源码包已过时。如图:

二、提供包级别的变量
介绍
如果想在包里面使用对应的变量,而不想让其他包使用,就可以将变量放到package-info.java下面,实现分包自用的理念。
样例
- 在package-info.java添加以下内容:
/** * 包类 */ class PACKAGE_CLASS{ public void test(){ } } /** * 包常量 */ class PACKAGE_CONST{ public static final String TEST_01="TEST"; }
- 在包内的任意类调用包常量,未报错:
public class Client { public static void main(String[] args) throws ClassNotFoundException { System.out.println(PACKAGE_CONST.TEST_01); } }

- 在包外的任意类调用包常量,提示报错:
public class Client { public static void main(String[] args) throws ClassNotFoundException { System.out.println(PACKAGE_CONST.TEST_01); } }

三、提供包级别的注释
介绍
使用JavaDoc的时候,通过在package-info.java添加注释,生成JavaDoc实现对应包的注释说明。
样例
- 添加对应的包的注释
@TestPkg @Deprecated package com.exercise.data_collection_error_info_transformation.component;
- 生成对应的JavaDoc文档,截图如下:

点击component的链接,截图如下: