天天看點

java包命名

為什麼把包命名單獨提出來呢?因為之前的命名一直是有問題的,被别人質疑了,是以這裡單獨提出來記錄一下。

問題是關于包名裡的下劃線(_)是使用,如果包名的一個層級是多個單詞,該不該用下劃線分割呢?

答案是不能,多個單詞也要使用小寫命名,不能用下劃線分割。

下面是摘自官方文檔的一句話:

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as “int”. In this event, the suggested convention is to add an underscore.

可以看出來,包名要始終以小寫單詞命名,即使需要多個單詞作為一個層級,也要小寫在一起,比如springframework,沒有下劃線,當然除了以下情況例外需要以下劃線标示:

1. 某個層次名稱裡有特殊字元,比如name-chengdu作為包名,要命名為: name_chengdu。

2. 層次名稱裡有Java的關鍵字,比如int.example,我們要命名為int_.example。

3. 層次名稱以數字開頭,比如com.123name.utils,要命名為com._123name.utils。

這裡小計一下,避免以後忘記。