package-info.java到底是什么

发现距离上一次在这里写博客已经三个多月了。。。说好的笔耕不辍呢=.=

Anyway,今天(确切说是昨天晚上)在code review中被组里的QA II问到在一个叫做package-info.java的java文件中的一些字符串能不能定义成constant。这里先介绍一下这个叫做package-info.java的java文件的大概情况:有若干annotation,有package,有import,但是没有任何的class定义。我试了一下发现如果想要在这里定义一个class,因为class名中不允许有“-”,所以是行不通的,当然也可以在外面新建一个java class然后放上static final string,不过显然为了两三个只在一个package里面用到的string而搞一个java class有点overkill了。。。于是解释说好像不是个好主意,然后cr过了。上班时由于sprint有任务时间稍紧,所以也没太追究这个名字首字母小写且没有任何class定义的java file到底是何方神圣。

下班之后又意外发现在intellij里面如果右键new东西的话居然有个选项是new一个package-info.java。。。简直醉了,既然这么有缘分那咱就google一下看看你到底是神马玩意吧!

这一google才发现原来这玩意不是我司内部的玩意,在http://www.intertech.com/Blog/whats-package-info-java-for/ 中作者详细介绍了这个package-info.java到底是什么,干了什么,以及为什么。原文截取如下:

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.

The package-info.java file above must sit in the com.intertech.services package.

Package Documentation

Prior to Java 5, package level documentation (the documentation shown in Javadocs for a package) was placed in package.html.  Today, the description and other related documentation for a package can be written up in the package-info.java file and it gets used in the production of the Javadocs.  As a demonstration, the example package-info.java…

 1 /**
 2  * DOMAIN CLASSES USED TO PRODUCE THE JSON AND XML OUTPUT FOR THE RESTFUL SERVICES. 
 3  * <P>
 4  * THESE CLASSES CONTAIN THE JAXB ANNOTATIONS.
 5  *
 6  * @SINCE 1.0
 7  * @AUTHOR JWHITE
 8  * @VERSION 1.1
 9  */
10 package com.intertech.cms.domain;

… results in the following Javadocs.

package-info.java到底是什么_第1张图片

 

Package Annotations

Perhaps more importantly to today’s annotation driven programmer, the package-info.java file contains package level annotations. An annotation with ElementType.PACKAGE as one of its targets is a package-level annotation and there are many of them.  Using your favorite IDE’s code assistant (shown in Eclipse below) in a package-info.java file and you will find a number package annotation options.

package-info.java到底是什么_第2张图片

For example, perhaps you want to deprecate all the types in a package. You could annotate each individual type (the classes, interfaces, enums, etc. defined in their .java files) with @Deprecated (as shown below).

1 @Deprecated
2 public class Contact {
3 }

Or, you could use the @Deprecated on the package declaration in package-info.java.  This has the effect of deprecating everything in the package in one fell swoop.

@Deprecated
package com.intertech.cms.domain;

 

你可能感兴趣的:(package-info.java到底是什么)