在阅读一些开源的Java Source Code时,我们通常会发现在每个package的下面,会有一个这样的文件:
package-info.java
乍看之下,它并不符合Java类的命名规范。在Eclipse是无法直接创建这个类的,可以先创建一个其它名字的类,再rename回来。
而且打开这个文件,通常会发现里面没有类申明,只有这个包的申明,和包上的Javadoc注释,当然,包级别的Annotation也会使用在这个类里面。
如果这个类不包含包级别的Annotation,是没有必要一定需要这个名字的,如果有包级别的Annotation,Eclipse会提示“Package annotations must be in file package-info.java”
其实,通常这个文件有三个作用:
1.为标注在包上Annotation提供便利
2.申明包级别的私有类和变量
3.提供包级别的整体注释
以下是示例:
- package pkg.info;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Target(ElementType.PACKAGE)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface PkgAnnotation {
- }
package pkg.info;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PkgAnnotation {
}
- /**
- *
- * <b>package-info has three function</b><br>
- * 1.package annotation<br>
- * 2.package level class and constant<br>
- * 3.package level comment<br>
- */
- //这个文件是无法声明公共类的,否则类名必须与文件名相同。
- @PkgAnnotation
- package pkg.info;
- //包级别的私有类
- class Test{
- public void sayHi(){
- System.out.println("Hi");
- }
- }
- //定义包级别的常量
- class Constant{
- public static final String NAME = "abc";
- }
- package pkg.info;
- import java.lang.annotation.Annotation;
- public class Client {
- public static void main(String[] args) {
- Annotation[] annotations = Client.class.getPackage().getAnnotations();
- for (Annotation an : annotations) {
- if (an instanceof PkgAnnotation) {
- System.out.println("This is pkg annotation");
- }
- }
- System.out.println(Constant.NAME);
- Test test = new Test();
- test.sayHi();
- }
- }
/**
*
* <b>package-info has three function</b><br>
* 1.package annotation<br>
* 2.package level class and constant<br>
* 3.package level comment<br>
*/
//这个文件是无法声明公共类的,否则类名必须与文件名相同。
@PkgAnnotation
package pkg.info;
//包级别的私有类
class Test{
public void sayHi(){
System.out.println("Hi");
}
}
//定义包级别的常量
class Constant{
public static final String NAME = "abc";
}
package pkg.info;
import java.lang.annotation.Annotation;
public class Client {
public static void main(String[] args) {
Annotation[] annotations = Client.class.getPackage().getAnnotations();
for (Annotation an : annotations) {
if (an instanceof PkgAnnotation) {
System.out.println("This is pkg annotation");
}
}
System.out.println(Constant.NAME);
Test test = new Test();
test.sayHi();
}
}
这个包在运行JavaDoc后会产生如下结果: