發現距離上一次在這里寫博客已經三個多月了。。。說好的筆耕不輟呢=.=
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…
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 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).
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;