天天看点

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。

这里小计一下,避免以后忘记。