This is a nice tool to get a unified look for all the imports of a codebase. A custom import order rule is set in the TreeWalker module (Checker->TreeWalker). Eg.
<module name="Checker"> <property name="severity" value="warning"> <module name="TreeWalker"> <module name="CustomImportOrder"> <property name="customImportOrderRules" value=" STANDARD_JAVA_PACKAGE###THIRD_PARTY_PACKAGE###SPECIAL_IMPORT ###SAME_PACKAGE(3)###STATIC"> <property name="standardPackageRegExp" value="java\.|javax\."/> <property name="thirdPartyPackageRegExp" value="org\.|com\."/> <property name="specialImportsRegExp" value="se.my.packages*"/> ...
In the example above then following rules apply:
customImportOrderRules – this sets the order of the imports. Here the order is set as:
- STANDARD_JAVA_PACKAGE (Eg. imports that contains the words “java.” or “javax.”)
- THIRD_PARTY_PACKAGE (Eg. imports that contains the words “org.” or “com.”)
- SPECIAL_IMPORT (Eg. imports that starts with the text “se.my.packages”)
- SAME_PACKAGE(3). Packages in the same module. The number defines then depth were a package should be considered “the same”. Eg. a 3 means that all packages that share the 3 first modules are considered the same, eg. “java.util.concurrent.AbstractExecutorService” and “java.util.concurrent.locks.LockSupport” are considered the same as the share “java.util.concurrent”
- STATIC. Static packages (packages that have the static keyword in them, eg. import static se.my.package…)
standardPackageRegExp – this defines what is to be considered a “standard package” in the project. Use regular expression to match import strings that should be included. Correlates with STANDARD_JAVA_PACKAGE in “customImportOrderRules” property
thirdPartyPackageRegExp – defines the third party packages in the project. Use regular expression to match import strings that should be included. Correlates with THIRD_PARTY_PACKAGE in “customImportOrderRules” property
specialImportsRegExp – defines the special packages. Use regular expression to match import strings that should be included. Correlates with SPECIAL_IMPORTS in “customImportOrderRules” property
Rules are evaluated in priority order, so an import can only match one rule:
- STATIC
- SAME_PACKAGE
- STANDARD_JAVA_PACKAGE and SPECIAL_IMPORTS – longest match wins
- THIRD_PACKAGE
Custom import order can help to unify your code but it is quite a handfull to configure. This will hopefully help you configure yours
Tested with Checkstyle v8.14