Since Checkstyle 3.0
Checks that there are no import statements that use the *
notation.
Rationale: Importing all classes from a package or static members from a class leads to tight coupling between packages or classes and might lead to problems when a new version of a library introduces name clashes.
Note that property excludes
is not recursive,
subpackages of excluded packages are not automatically excluded.
name | description | type | default value | since |
---|---|---|---|---|
excludes | Specify packages where star imports are allowed. | String[] | {} |
3.2 |
allowClassImports |
Control whether to allow starred class imports like
import java.util.*; .
|
boolean | false |
5.3 |
allowStaticMemberImports |
Control whether to allow starred static member imports like
import static org.junit.Assert.*; .
|
boolean | false |
5.3 |
To configure the check:
<module name="AvoidStarImport"/>
Example:
import java.util.Scanner; // OK import java.io.*; // violation import static java.lang.Math.*; // violation import java.util.*; // violation import java.net.*; // violation
To configure the check so that star imports from packages
java.io and java.net
as well as static members from class
java.lang.Math
are allowed:
<module name="AvoidStarImport"> <property name="excludes" value="java.io,java.net,java.lang.Math"/> </module>
Example:
import java.util.Scanner; // OK import java.io.*; // OK import static java.lang.Math.*; // OK import java.util.*; // violation import java.net.*; // OK
To configure the check so that star imports from all packages are allowed:
<module name="AvoidStarImport"> <property name="allowClassImports" value="true"/> </module>
Example:
import java.util.Scanner; // OK import java.io.*; // OK import static java.lang.Math.*; // violation import java.util.*; // OK import java.net.*; // OK
To configure the check so that starred static member imports from all packages are allowed:
<module name="AvoidStarImport"> <property name="allowStaticMemberImports" value="true"/> </module>
Example:
import java.util.Scanner; // OK import java.io.*; // violation import static java.lang.Math.*; // OK import java.util.*; // violation import java.net.*; // violation
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 5.0
Checks that there are no static import statements.
Rationale: Importing static members can lead to naming conflicts between class' members. It may lead to poor code readability since it may no longer be clear what class a member resides in (without looking at the import statement).
If you exclude a starred import on a class this automatically excludes each member individually.
For example: Excluding java.lang.Math.*
. will allow the
import of each static member in the Math class
individually like java.lang.Math.PI, java.lang.Math.cos, ...
.
name | description | type | default value | since |
---|---|---|---|---|
excludes |
Control whether to allow for certain classes via a star notation to be
excluded such as java.lang.Math.* or specific static
members to be excluded like java.lang.System.out for a variable or
java.lang.Math.random for a method. See notes section for details.
|
String[] | {} |
5.0 |
To configure the check:
<module name="AvoidStaticImport"/>
Example:
import static java.lang.Math.pow; // violation import static java.lang.System.*; // violation import java.io.File; // OK import java.util.*; // OK
To configure the check so that the java.lang.System.out
member and all members from java.lang.Math
are allowed:
<module name="AvoidStaticImport"> <property name="excludes" value="java.lang.System.out,java.lang.Math.*"/> </module>
Example:
import static java.lang.Math.*; // OK import static java.lang.System.out; // OK import static java.lang.Integer.parseInt; // violation import java.io.*; // OK import java.util.*; // OK
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 5.8
Checks that the groups of import declarations appear in the order specified by the user. If there is an import but its group is not specified in the configuration such an import should be placed at the end of the import list.
The rule consists of:
package java.util.concurrent.locks; import java.io.File; import java.util.*; //#1 import java.util.List; //#2 import java.util.StringTokenizer; //#3 import java.util.concurrent.*; //#4 import java.util.concurrent.AbstractExecutorService; //#5 import java.util.concurrent.locks.LockSupport; //#6 import java.util.regex.Pattern; //#7 import java.util.regex.Matcher; //#8
Use the separator '###' between rules.
To set RegExps for THIRD_PARTY_PACKAGE and STANDARD_JAVA_PACKAGE groups use thirdPartyPackageRegExp and standardPackageRegExp options.
Pretty often one import can match more than one group. For example, static import from standard package or regular expressions are configured to allow one import match multiple groups. In this case, group will be assigned according to priorities:
Few examples to illustrate "best match":
1. patterns STANDARD_JAVA_PACKAGE = "Check", SPECIAL_IMPORTS="ImportOrderCheck" and input file:
import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; import com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck;
Result: imports will be assigned to SPECIAL_IMPORTS, because matching substring length is 16. Matching substring for STANDARD_JAVA_PACKAGE is 5.
2. patterns STANDARD_JAVA_PACKAGE = "Check", SPECIAL_IMPORTS="Avoid" and file:
import com.puppycrawl.tools.checkstyle.checks.imports.AvoidStarImportCheck;
Result: import will be assigned to SPECIAL_IMPORTS. Matching substring length is 5 for both patterns. However, "Avoid" position is lower than "Check" position.
name | description | type | default value | since |
---|---|---|---|---|
customImportOrderRules | Specify format of order declaration customizing by user. | String | "" |
5.8 |
standardPackageRegExp | Specify RegExp for STANDARD_JAVA_PACKAGE group imports. | Pattern | "^(java|javax)\." |
5.8 |
thirdPartyPackageRegExp | Specify RegExp for THIRD_PARTY_PACKAGE group imports. | Pattern | ".*" |
5.8 |
specialImportsRegExp | Specify RegExp for SPECIAL_IMPORTS group imports. | Pattern | "^$" |
5.8 |
separateLineBetweenGroups | Force empty line separator between import groups. | boolean | true |
5.8 |
sortImportsInGroupAlphabetically | Force grouping alphabetically, in ASCII sort order. | boolean | false |
5.8 |
To configure the check so that it matches default Eclipse formatter configuration (tested on Kepler and Luna releases):
Notes:
<module name="CustomImportOrder"> <property name="customImportOrderRules" value="STATIC###STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS"/> <property name="specialImportsRegExp" value="^org\."/> <property name="sortImportsInGroupAlphabetically" value="true"/> <property name="separateLineBetweenGroups" value="true"/> </module>
To configure the check so that it matches default Eclipse formatter configuration (tested on Mars release):
<module name="CustomImportOrder"> <property name="customImportOrderRules" value="STATIC###STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE"/> <property name="specialImportsRegExp" value="^org\."/> <property name="thirdPartyPackageRegExp" value="^com\."/> <property name="sortImportsInGroupAlphabetically" value="true"/> <property name="separateLineBetweenGroups" value="true"/> </module>
To configure the check so that it matches default IntelliJ IDEA formatter configuration (tested on v14):
Note: "separated" option is disabled because IDEA default has blank line between "java" and static imports, and no blank line between "javax" and "java"
<module name="CustomImportOrder"> <property name="customImportOrderRules" value="THIRD_PARTY_PACKAGE###SPECIAL_IMPORTS###STANDARD_JAVA_PACKAGE###STATIC"/> <property name="specialImportsRegExp" value="^javax\."/> <property name="standardPackageRegExp" value="^java\."/> <property name="sortImportsInGroupAlphabetically" value="true"/> <property name="separateLineBetweenGroups" value="false"/> </module>
To configure the check so that it matches default NetBeans formatter configuration (tested on v8):
<module name="CustomImportOrder"/>
To set RegExps for THIRD_PARTY_PACKAGE and STANDARD_JAVA_PACKAGE groups use thirdPartyPackageRegExp and standardPackageRegExp options.
<module name="CustomImportOrder"> <property name="customImportOrderRules" value="STATIC###SAME_PACKAGE(3)###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/> <property name="thirdPartyPackageRegExp" value="^(com|org)\."/> <property name="standardPackageRegExp" value="^(java|javax)\."/> </module>
Also, this check can be configured to force empty line separator between import groups. For example.
<module name="CustomImportOrder"> <property name="separateLineBetweenGroups" value="true"/> </module>
It is possible to enforce ASCII sort order of imports in groups using the following configuration:
<module name="CustomImportOrder"> <property name="sortImportsInGroupAlphabetically" value="true"/> </module>
Example of ASCII order:
import java.awt.Dialog; import java.awt.Window; import java.awt.color.ColorSpace; import java.awt.Frame; // violation here - in ASCII order 'F' should go before 'c', // as all uppercase come before lowercase letters
To force checking imports sequence such as:
package com.puppycrawl.tools.checkstyle.imports; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import org.abego.treelayout.Configuration; import static sun.tools.util.ModifierFilter.ALL_ACCESS; import com.google.common.annotations.GwtCompatible; // violation here - should be in the // THIRD_PARTY_PACKAGE group import android.*;
configure as follows:
<module name="CustomImportOrder"> <property name="customImportOrderRules" value="SAME_PACKAGE(3)###THIRD_PARTY_PACKAGE###STATIC###SPECIAL_IMPORTS"/> <property name="specialImportsRegExp" value="^android\."/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 3.0
Checks for imports from a set of illegal packages.
Note: By default, the check rejects all sun.*
packages since
programs that contain direct calls to the sun.*
packages are
"not guaranteed to work on all Java-compatible platforms".
To reject other packages, set property illegalPkgs
to
a list of the illegal packages.
name | description | type | default value | since |
---|---|---|---|---|
illegalPkgs | Specify packages to reject, if regexp property is not set, checks if import is the part of package. If regexp property is set, then list of packages will be interpreted as regular expressions. Note, all properties for match will be used. | String[] | sun |
3.0 |
illegalClasses | Specify class names to reject, if regexp property is not set, checks if import equals class name. If regexp property is set, then list of class names will be interpreted as regular expressions. Note, all properties for match will be used. | String[] | {} |
7.8 |
regexp |
Control whether the illegalPkgs and illegalClasses
should be interpreted as regular expressions.
|
boolean | false |
7.8 |
To configure the check:
<module name="IllegalImport"/>
To configure the check so that it rejects packages java.io.*
and java.sql.*
:
<module name="IllegalImport"> <property name="illegalPkgs" value="java.io, java.sql"/> </module>
The following example shows class with no illegal imports
import java.lang.ArithmeticException; import java.util.List; import java.util.Enumeration; import java.util.Arrays; import sun.applet.*; public class InputIllegalImport { }
The following example shows class with two illegal imports
import java.io.*; // violation import java.lang.ArithmeticException; import java.sql.Connection; // violation import java.util.List; import java.util.Enumeration; import java.util.Arrays; import sun.applet.*; public class InputIllegalImport { }
To configure the check so that it rejects classes java.util.Date
and
java.sql.Connection
:
<module name="IllegalImport"> <property name="illegalClasses" value="java.util.Date, java.sql.Connection"/> </module>
The following example shows class with no illegal imports
import java.io.*; import java.lang.ArithmeticException; import java.util.List; import java.util.Enumeration; import java.util.Arrays; import sun.applet.*; public class InputIllegalImport { }
The following example shows class with two illegal imports
import java.io.*; import java.lang.ArithmeticException; import java.sql.Connection; // violation import java.util.List; import java.util.Enumeration; import java.util.Arrays; import java.util.Date; // violation import sun.applet.*; public class InputIllegalImport { }
To configure the check so that it rejects packages not satisfying to regular
expression java\.util
:
<module name="IllegalImport"> <property name="regexp" value="true"/> <property name="illegalPkgs" value="java\.util"/> </module>
The following example shows class with no illegal imports
import java.io.*; import java.lang.ArithmeticException; import java.sql.Connection; import sun.applet.*; public class InputIllegalImport { }
The following example shows class with four illegal imports
All four imports match "java\.util" regular expression
import java.io.*; import java.lang.ArithmeticException; import java.sql.Connection; import java.util.List; // violation import java.util.Enumeration; // violation import java.util.Arrays; // violation import java.util.Date; // violation import sun.applet.*; public class InputIllegalImport { }
To configure the check so that it rejects class names not satisfying to regular
expression ^java\.util\.(List|Arrays)
and
^java\.sql\.Connection
:
<module name="IllegalImport"> <property name="regexp" value="true"/> <property name="illegalClasses" value="^java\.util\.(List|Arrays), ^java\.sql\.Connection"/> </module>
The following example shows class with no illegal imports
import java.io.*; import java.lang.ArithmeticException; import java.util.Enumeration; import java.util.Date; import sun.applet.*; public class InputIllegalImport { }
The following example shows class with three illegal imports
import java.io.*; import java.lang.ArithmeticException; import java.sql.Connection; // violation import java.util.List; // violation import java.util.Enumeration; import java.util.Arrays; // violation import java.util.Date; import sun.applet.*; public class InputIllegalImport { }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 4.0
Controls what can be imported in each package and file. Useful for ensuring that application layering rules are not violated, especially on large projects.
You can control imports based on the a package name or based on the file name. When controlling packages, all files and sub-packages in the declared package will be controlled by this check. To specify differences between a main package and a sub-package, you must define the sub-package inside the main package. When controlling file, only the file name is considered and only files processed by TreeWalker. The file's extension is ignored.
Short description of the behaviour:
The DTD for a import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. It contains documentation on each of the elements and attributes.
The check validates a XML document when it loads the document. To validate against the above DTD, include the following document type declaration in your XML document:
<!DOCTYPE import-control PUBLIC "-//Checkstyle//DTD ImportControl Configuration 1.4//EN" "https://checkstyle.org/dtds/import_control_1_4.dtd">
name | description | type | default value | since |
---|---|---|---|---|
file | Specify the location of the file containing the import control configuration. It can be a regular file, URL or resource path. It will try loading the path as a URL first, then as a file, and finally as a resource. | URI | null |
4.0 |
path | Specify the regular expression of file paths to which this check should apply. Files that don't match the pattern will not be checked. The pattern will be matched against the full absolute file path. | Pattern | ".*" |
7.5 |
To configure the check using an import control file called "config/import-control.xml", then have the following:
<module name="ImportControl"> <property name="file" value="config/import-control.xml"/> </module>
To configure the check to only check the "src/main" directory using an import control file called "config/import-control.xml", then have the following:
<module name="ImportControl"> <property name="file" value="config/import-control.xml"/> <property name="path" value="^.*[\\/]src[\\/]main[\\/].*$"/> </module>
In the example below access to package
com.puppycrawl.tools.checkstyle.checks
and its subpackages is
allowed from anywhere in com.puppycrawl.tools.checkstyle
except
from the filters
subpackage where access to all
check
's subpackages is disallowed. Two java.lang.ref
classes are allowed by virtue of one regular expression instead of listing
them in two separate allow rules (as it is done with the Files
and ClassPath
classes).
<import-control pkg="com.puppycrawl.tools.checkstyle"> <disallow pkg="sun"/> <allow pkg="com.puppycrawl.tools.checkstyle.api"/> <allow pkg="com.puppycrawl.tools.checkstyle.checks"/> <allow class="com.google.common.io.Files"/> <allow class="com.google.common.reflect.ClassPath"/> <subpackage name="filters"> <allow class="java\.lang\.ref\.(Weak|Soft)Reference" regex="true"/> <disallow pkg="com\.puppycrawl\.tools\.checkstyle\.checks\.[^.]+" regex="true"/> <disallow pkg="com.puppycrawl.tools.checkstyle.ant"/> <disallow pkg="com.puppycrawl.tools.checkstyle.gui"/> </subpackage> <subpackage name="dao"> <disallow pkg="javax.swing" exact-match="true"/> </subpackage> </import-control>
In the next example regular expressions are used to enforce a layering rule: In all
dao
packages it is not allowed to access UI layer code (ui
,
awt
, and swing
). On the other hand it is not allowed to directly
access dao
and service
layer from ui
packages. The
root package is also a regular expression that is used to handle old and new domain name
with the same rules.
<import-control pkg="(de.olddomain|de.newdomain)\..*" regex="true"> <subpackage pkg="[^.]+\.dao" regex="true"> <disallow pkg=".*\.ui" regex="true"/> <disallow pkg=".*\.(awt|swing).\.*" regex="true"/> </subpackage> <subpackage pkg="[^.]+\.ui" regex="true"> <disallow pkg=".*\.(dao|service)" regex="true"/> </subpackage> </import-control>
In the next examples usage of strategyOnMismatch
property is shown.
This property defines strategy in a case when no matching allow/disallow rule was found.
Property strategyOnMismatch
is attribute of import-control
and
subpackage
tags.
Property can have following values for import-control
tag:
And following values for subpackage
tags:
The following example demonstrates usage of strategyOnMismatch
property for
import-control
tag. Here all imports are allowed except
java.awt.Image
and java.io.File
classes.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks" strategyOnMismatch="allowed"> <disallow class="java.awt.Image"/> <disallow class="java.io.File"/> </import-control>
In the example below, any import is disallowed inside
com.puppycrawl.tools.checkstyle.checks.imports
package except imports from
package javax.swing
and class java.io.File
.
However, any import is allowed in the classes outside of
com.puppycrawl.tools.checkstyle.checks.imports
package.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks" strategyOnMismatch="allowed"> <subpackage name="imports" strategyOnMismatch="disallowed"> <allow pkg="javax.swing"/> <allow class="java.io.File"/> </subpackage> </import-control>
When strategyOnMismatch
has allowed
or disallowed
value for subpackage
tag, it makes subpackage
isolated from
parent rules.
In the next example, if no matching rule was found inside
com.puppycrawl.tools.checkstyle.checks.filters
then it continues checking
in the parent subpackage, while for
com.puppycrawl.tools.checkstyle.checks.imports
import will be allowed by
default.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks"> <allow class="java\.awt\.Image" regex="true"/> <allow class="java\..*\.File" local-only="true" regex="true"/> <subpackage name="imports" strategyOnMismatch="allowed"> <allow pkg="javax\.swing" regex="true"/> <allow pkg="java\.io" exact-match="true" local-only="true" regex="true"/> </subpackage> <subpackage name="filters"> <allow class="javax.util.Date"/> </subpackage> </import-control>
In the example below, only file names that end with "Panel", "View", or "Dialog"
in the package gui
are disallowed to have imports from
com.mycompany.dao
and any jdbc
package. In addition, only
the file name named "PresentationModel" in the package gui
are
disallowed to have imports that match javax.swing.J*
.
All other imports in the package are allowed.
<import-control pkg="com.mycompany.billing"> <subpackage name="gui" strategyOnMismatch="allowed"> <file name=".*(Panel|View|Dialog)" regex="true"> <disallow pkg="com.mycompany.dao"/> <disallow pkg=".*\.jdbc" regex="true"/> </file> <file name="PresentationModel"> <disallow pkg="javax\.swing\.J.*" regex="true"/> </file> </subpackage> </import-control>
For a real-life import control file look at the file called import-control.xml which is part of the Checkstyle distribution.
To have a blacklist mode, it is required to have disallows inside subpackage and to have allow rule inside parent of the current subpackage to catch classes and packages those are not in the blacklist.
In the example below any import from java.util
(java.util.List
, java.util.Date
) package is allowed except
java.util.Map
inside subpackage
com.puppycrawl.tools.checkstyle.filters
.
<import-control pkg="com.puppycrawl.tools.checkstyle"> <allow pkg="java.util"/> <subpackage name="filters" > <disallow class="java.util.Map"/> </subpackage> </import-control>
In the next example imports java.util.stream.Stream
and
java.util.stream.Collectors
are disallowed inside
com.puppycrawl.tools.checkstyle.checks.imports
package,
but because of <allow pkg="java.util.stream"/>
every import
from java.util.stream
is allowed except described ones.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks"> <allow pkg="java.util.stream"/> <subpackage name="imports"> <disallow class="java.util.stream.Stream"/> <disallow class="java.util.stream.Collectors"/> </subpackage> </import-control>
package com.puppycrawl.tools.checkstyle.checks.imports; import java.util.stream.Stream; // violation here import java.util.stream.Collectors; // violation here import java.util.stream.IntStream;
In the following example, all imports are allowed except the classes
java.util.Date
, java.util.List
and package sun
.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks"> <allow pkg=".*" regex="true"/> <subpackage name="imports"> <disallow class="java.util.Date"/> <disallow class="java.util.List"/> <disallow pkg="sun"/> </subpackage> </import-control>
In the following example, all imports of the java.util
package are allowed
except the java.util.Date
class.
<import-control pkg="com.puppycrawl.tools.checkstyle.checks"> <disallow class="java.util.Date"/> <allow pkg="java.util"/> </import-control>
Regular expressions in import rules have to match either Java packages or classes. The language rules for packages and class names can be described by the following complicated regular expression that takes into account that Java names may contain any unicode letter, numbers, underscores, and dollar signs (see section 3.8 in the Java specs):
[\p{Letter}_$][\p{Letter}\p{Number}_$]*
or short
[\p{L}_$][\p{L}\p{N}_$]*
for a class name or package component.
([\p{L}_$][\p{L}\p{N}_$]*\.)*[\p{L}_$][\p{L}\p{N}_$]*
for a fully qualified name.
But it is not necessary to use these complicated expressions since no validation is
required. Differentiating between package separator '.' and others is
sufficient. Unfortunately '.' has a special meaning in regular expressions so one has
to write \.
to match an actual dot.
[^.]+
(one or more "not a dot" characters) for a class name or
package component.
com\.google\.common\.[^.]+
to match any subpackage of
com.google.common
.
com.google.common
omitting the
backslash before the dots may improve readability and may be just exact enough:
com.google.common\.[^.]+
matches not only subpackages of
com.google.common
but e.g. also of com.googleecommon
but
you may not care for that.
.*
unless you really do not care for what is matched. Often
you want to match only a certain package level instead.
Static members (including methods, constants and static inner classes) have to be explicitly allowed when they are imported, they are not automatically allowed along with their enclosing class.
For example, to allow importing both java.util.Map
and
java.util.Map.Entry
use the following configuration:
<import-control pkg="com.puppycrawl.tools.checkstyle"> <allow class="java.util.Map"/> <allow class="java.util.Map.Entry"/> </import-control>
It is also possible to use a regex with a wildcard:
<import-control pkg="com.puppycrawl.tools.checkstyle"> <allow class="java.util.Map"/> <allow class="java.util.Map.*" regex="true" /> </import-control>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 3.2
Checks the ordering/grouping of imports. Features are:
name | description | type | default value | since |
---|---|---|---|---|
option | specify policy on the relative order between type imports and static imports. | ImportOrderOption | under |
5.0 |
groups |
specify list of type import groups (every group identified either by a
common prefix string, or by a regular expression enclosed
in forward slashes (e.g. /regexp/ ). All type imports,
which does not match any group, falls into an additional group, located at the end.
Thus, the empty list of type groups (the default value) means
one group for all type imports.
|
Regular Expressions | {} |
3.2 |
ordered | control whether type imports within each group should be sorted. It doesn't affect sorting for static imports. | boolean | true |
3.2 |
separated | control whether type import groups should be separated by, at least, one blank line or comment and aren't separated internally. It doesn't affect separations for static imports. | boolean | false |
3.2 |
separatedStaticGroups |
control whether static import groups should be separated by, at least, one
blank line or comment and aren't separated internally.
This property has effect only when the property option
is set to top or bottom and when property
staticGroups is enabled.
|
boolean | false |
8.12 |
caseSensitive | control whether string comparison should be case sensitive or not. Case sensitive sorting is in ASCII sort order. It affects both type imports and static imports. | boolean | true |
3.3 |
staticGroups |
specify list of static import groups (every group identified either by a
common prefix string, or by a regular expression enclosed
in forward slashes (e.g. /regexp/ ). All static imports,
which does not match any group, falls into an additional group, located at the
end. Thus, the empty list of static groups (the default value) means
one group for all static imports. This property has effect only when
the property option is set to top or
bottom .
|
Regular Expressions | {} |
8.12 |
sortStaticImportsAlphabetically | control whether static imports located at top or bottom are sorted within the group. | boolean | false |
6.5 |
useContainerOrderingForStatic | control whether to use container ordering (Eclipse IDE term) for static imports or not. | boolean | false |
7.1 |
tokens | tokens to check | subset of tokens STATIC_IMPORT . | STATIC_IMPORT . | 3.2 |
To configure the check:
<module name="ImportOrder"/>
Example:
import java.io.IOException; import java.net.URL; import java.io.IOException; // violation, extra separation before import // and wrong order, comes before 'java.net.URL'. import javax.net.ssl.TrustManager; // violation, extra separation due to above comment import javax.swing.JComponent; import org.apache.http.conn.ClientConnectionManager; // OK import java.util.Set; // violation, wrong order, 'java' should not come after 'org' imports import com.neurologic.http.HttpClient; // violation, wrong order, 'com' imports comes at top import com.neurologic.http.impl.ApacheHttpClient; // OK public class SomeClass { }
To configure the check so that it matches default Eclipse formatter configuration (tested on Kepler and Luna releases):
Notes:
<module name="ImportOrder"> <property name="groups" value="/^java\./,javax,org"/> <property name="ordered" value="true"/> <property name="separated" value="true"/> <property name="option" value="above"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module>
Example:
import static java.lang.System.out; import static java.lang.Math; // violation, alphabetical case sensitive ASCII order, 'M' < 'S' import java.io.IOException; import java.net.URL; // violation, extra separation before import import java.security.KeyManagementException; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; // violation, groups should not be separated internally import org.apache.http.conn.ClientConnectionManager; public class SomeClass { }
To configure the check so that it matches default Eclipse formatter configuration (tested on Mars release):
<module name="ImportOrder"> <property name="groups" value="/^java\./,javax,org,com"/> <property name="ordered" value="true"/> <property name="separated" value="true"/> <property name="option" value="above"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module>
Example:
import static java.io.File.createTempFile; import static java.lang.Math.abs; // OK, alphabetical case sensitive ASCII order, 'i' < 'l' import java.lang.Math.sqrt; // OK, follows property 'Option' value 'above' import java.io.File; // violation, alphabetical case sensitive ASCII order, 'i' < 'l' import java.io.IOException; // violation, extra separation in 'java' import group import org.albedo.*; import static javax.WindowConstants.*; // violation, wrong order, 'javax' comes before 'org' import javax.swing.JComponent; import org.apache.http.ClientConnectionManager; // violation, must separate from previous import import org.linux.apache.server.SoapServer; // OK import com.neurologic.http.HttpClient; // OK import com.neurologic.http.impl.ApacheHttpClient; // OK public class SomeClass { }
To configure the check so that it matches default IntelliJ IDEA formatter configuration (tested on v2018.2):
Note: a suppression xpath single filter is needed because IDEA has no blank line between "javax" and "java". ImportOrder has a limitation by design to enforce an empty line between groups ("java", "javax"). There is no flexibility to enforce empty lines between some groups and no empty lines between other groups.
Note: "separated" option is disabled because IDEA default has blank line between "java" and static imports, and no blank line between "javax" and "java".
<module name="ImportOrder"> <property name="groups" value="*,javax,java"/> <property name="ordered" value="true"/> <property name="separated" value="false"/> <property name="option" value="bottom"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module> <module name="SuppressionXpathSingleFilter"> <property name="checks" value="ImportOrder"/> <property name="message" value="^'java\..*'.*"/> </module>
Example:
import com.neurologic.http.impl.ApacheHttpClient; // OK import static java.awt.Button.A; import javax.swing.JComponent; // violation, wrong order, caused by above static import // all static imports comes at bottom import java.net.URL; // violation, extra separation in import group import java.security.KeyManagementException; import javax.swing.JComponent; // violation, wrong order, 'javax' should be above 'java' imports import com.neurologic.http.HttpClient; // violation, wrong order, 'com' imports should be at top public class TestClass { }
To configure the check so that it matches default NetBeans formatter configuration (tested on v8):
<module name="ImportOrder"> <property name="option" value="inflow"/> </module>
Example:
import static java.io.File.createTempFile; import java.lang.Math.sqrt; import javax.swing.JComponent; // violation, extra separation in import group import static javax.windowConstants.*; // OK // all static imports are processed like non static imports. public class SomeClass { }
Group descriptions enclosed in slashes are interpreted as regular expressions. If multiple groups match, the one matching a longer substring of the imported name will take precedence, with ties broken first in favor of earlier matches and finally in favor of the first matching group.
There is always a wildcard group to which everything not in a named group belongs. If an import does not match a named group, the group belongs to this wildcard group. The wildcard group position can be specified using the {@code *} character.
Check also has on option making it more flexible: sortStaticImportsAlphabetically - sets whether static imports grouped by top or bottom option should be sorted alphabetically or not, default value is false. It is applied to static imports grouped with top or bottom options. This option is helping in reconciling of this Check and other tools like Eclipse's Organize Imports feature.
To configure the Check allows static imports grouped to the top being sorted alphabetically:
<module name="ImportOrder"> <property name="sortStaticImportsAlphabetically" value="true"/> <property name="option" value="top"/> </module>
import static java.lang.Math.PI; import static java.lang.Math.abs; // OK, alphabetical case sensitive ASCII order, 'P' < 'a' import static org.abego.treelayout.Configuration.AlignmentInLevel; // OK, alphabetical order import java.util.Set; // violation, extra separation in import group import static java.lang.Math.abs; // violation, wrong order, all static imports comes at 'top' import org.abego.*; public class SomeClass { }
To configure the Check with groups of static imports:
<module name="ImportOrder"> <property name="staticGroups" value="org,java"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module>
import static org.abego.treelayout.Configuration.AlignmentInLevel; // Group 1 import static java.lang.Math.abs; // Group 2 import static java.lang.String.format; // Group 2 import static com.google.common.primitives.Doubles.BYTES; // Group "everything else" public class SomeClass { }
The following example shows the idea of 'useContainerOrderingForStatic' option that is useful for Eclipse IDE users to match ordering validation. This is how the import comparison works for static imports: we first compare the container of the static import, container is the type enclosing the static element being imported. When the result of the comparison is 0 (containers are equal), we compare the fully qualified import names. For e.g. this is what is considered to be container names for the given example: import static HttpConstants.COLON => HttpConstants import static HttpHeaders.addHeader => HttpHeaders import static HttpHeaders.setHeader => HttpHeaders import static HttpHeaders.Names.DATE => HttpHeaders.Names According to this logic, HttpHeaders.Names should come after HttpHeaders.
Example for useContainerOrderingForStatic=true
<module name="ImportOrder"> <property name="useContainerOrderingForStatic" value="true"/> <property name="ordered" value="true"/> <property name="option" value="top"/> <property name="caseSensitive" value="false"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module>
import static io.netty.handler.codec.http.HttpConstants.COLON; import static io.netty.handler.codec.http.HttpHeaders.addHeader; import static io.netty.handler.codec.http.HttpHeaders.setHeader; import static io.netty.handler.codec.http.HttpHeaders.Names.DATE; public class InputEclipseStaticImportsOrder { }
Example for useContainerOrderingForStatic=false
<module name="ImportOrder"> <property name="useContainerOrderingForStatic" value="false"/> <property name="ordered" value="true"/> <property name="option" value="top"/> <property name="caseSensitive" value="false"/> <property name="sortStaticImportsAlphabetically" value="true"/> </module>
import static io.netty.handler.codec.http.HttpConstants.COLON; import static io.netty.handler.codec.http.HttpHeaders.addHeader; import static io.netty.handler.codec.http.HttpHeaders.setHeader; import static io.netty.handler.codec.http.HttpHeaders.Names.DATE; // violation public class InputEclipseStaticImportsOrder { }
To configure the check to enforce static import group separation
Example for separatedStaticGroups=true
<module name="ImportOrder"> <property name="staticGroups" value="*,java,javax,org"/> <property name="option" value="top"/> <property name="separatedStaticGroups" value="true"/> </module>
import static java.lang.Math.PI; import static java.io.File.createTempFile; import static javax.swing.JComponent; // violation, should be separated from previous imports import static javax.WindowConstants.*; // OK import java.net.URL; public class SomeClass { }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 3.0
Checks for redundant import statements. An import statement is considered redundant if:
java.lang
package, e.g. importing java.lang.String
.
To configure the check:
<module name="RedundantImport"/>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports
Since Checkstyle 3.0
Checks for unused import statements. Checkstyle uses a simple but very reliable algorithm to report on unused import statements. An import statement is considered unused if:
import
java.io.*;
. Most IDE's provide very sophisticated checks
for imports that handle wild-card imports.
java.lang
package. For example importing java.lang.String
.
java.util.List
would be
considered referenced with the Javadoc comment
{@link List}
. The alternative to avoid introducing a
compile time dependency would be to write the Javadoc comment as
{@link java.util.List}
.
The main limitation of this check is handling the case where an imported type has the same name as a declaration, such as a member variable.
For example, in the following case the import java.awt.Component
will not be flagged as unused:
import java.awt.Component; class FooBar { private Object Component; // a bad practice in my opinion ... }
name | description | type | default value | since |
---|---|---|---|---|
processJavadoc | Control whether to process Javadoc comments. | boolean | true |
5.4 |
To configure the check:
<module name="UnusedImports"/>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.imports