您的位置:首页 > 编程语言 > Java开发

package-info.java到底是什么

2015-07-22 13:06 567 查看
发现距离上一次在这里写博客已经三个多月了。。。说好的笔耕不辍呢=.=

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.

1

package com.intertech.services;

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…

/**
* DOMAIN CLASSES USED TO PRODUCE THE JSON AND XML OUTPUT FOR THE RESTFUL SERVICES.
* <P>
* THESE CLASSES CONTAIN THE JAXB ANNOTATIONS.
*
* @SINCE 1.0
* @AUTHOR JWHITE
* @VERSION 1.1
*/
package com.intertech.cms.domain;


… results in the following Javadocs.









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.





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).

@Deprecated
public class Contact {
}


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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: