package-info.java’s purpose
The package-info.java is a Java file that can be added to any Java source package. Its purpose is to provide a home for package level documentation and package level annotations. Simply create the package-info.java file and add the package declaration that it relates to in the file. In fact, the only thing the package-info.java file must contain is the package declaration.
/** * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//** * Parsing utils */package org.apache.ibatis.parsing;
在Mybatis源码中无意中看到的
package-info.java的作用
主要作用为:
- 为标注在包上Annotation提供使用
- 声明包的私有类和常量
- 提供包的整体注释说明
Annotation
//MyAnnotation.java@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.PACKAGE)public @interface MyAnnotation { }//package-info.java/** * 我是一个包 -_- */@MyAnnotationpackage com.demo;// Test.javapublic class Test { public static void main(String[] args) { String packageName = "com.demo"; Package pkg = Package.getPackage(packageName); Annotation[] annotations = pkg.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof MyAnnotation){ System.out.println("MyAnnotation"); } } }}
声明包的私有类和常量
可以创建一些只有在这个包调用的私有类或者常量,其他包是不能访问的。
//package-info.javapackage com.demo;class MyClass{ void test() { System.out.println("MyClass.test()"); }}class MyConst { static final String str = "MyConst";}// Test.javapublic class Test { public static void main(String[] args) { MyClass myClass = new MyClass(); myClass.test(); System.out.println(MyConst.str); }}
提供包的整体注释说明
/** * Copyright 2009-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//** * Parsing utils */package org.apache.ibatis.parsing;
给这个包整体的注释说明 ,在生成JavaDoc文档时,会显示这些包注释。