Since Checkstyle 6.0
Checks location of annotation on language elements. By default, Check enforce to locate annotations immediately after documentation block and before target element, annotation should be located on separate line from target element. This check also verifies that the annotations are on the same indenting level as the annotated element if they are not on the same line.
Attention: Elements that cannot have JavaDoc comments like local variables are not in the
scope of this check even though a token type like VARIABLE_DEF
would match
them.
Attention: Annotations among modifiers are ignored (looks like false-negative) as there might be a problem with annotations for return types:
public @Nullable Long getStartTimeOrNull() { ... }
Such annotations are better to keep close to type. Due to limitations, Checkstyle can not examine the target of an annotation.
Example:
@Override @Nullable public String getNameIfPresent() { ... }
name | description | type | default value | since |
---|---|---|---|---|
allowSamelineMultipleAnnotations | Allow annotation(s) to be located on the same line as target element. | boolean | false |
6.0 |
allowSamelineSingleParameterlessAnnotation | Allow single parameterless annotation to be located on the same line as target element. | boolean | true |
6.1 |
allowSamelineParameterizedAnnotation | Allow one and only parameterized annotation to be located on the same line as target element. | boolean | false |
6.4 |
tokens | tokens to check | subset of tokens CLASS_DEF , INTERFACE_DEF , PACKAGE_DEF , ENUM_CONSTANT_DEF , ENUM_DEF , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , ANNOTATION_DEF , ANNOTATION_FIELD_DEF , RECORD_DEF , COMPACT_CTOR_DEF . | CLASS_DEF , INTERFACE_DEF , PACKAGE_DEF , ENUM_CONSTANT_DEF , ENUM_DEF , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . | 6.0 |
To configure the default check to allow one single parameterless annotation on the same line:
<module name="AnnotationLocation"/>
Example for above configuration:
@NotNull private boolean field1; //ok @Override public int hashCode() { return 1; } //ok @NotNull //ok private boolean field2; @Override //ok public boolean equals(Object obj) { return true; } @Mock DataLoader loader; //ok @SuppressWarnings("deprecation") DataLoader loader; //violation @SuppressWarnings("deprecation") public int foo() { return 1; } //violation @NotNull @Mock DataLoader loader; //violation
Use the following configuration to allow multiple annotations on the same line:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="true"/> <property name="allowSamelineSingleParameterlessAnnotation" value="false"/> <property name="allowSamelineParameterizedAnnotation" value="false"/> </module>
Example to allow any location multiple annotations:
@NotNull private boolean field1; //ok @Override public int hashCode() { return 1; } //ok @NotNull //ok private boolean field2; @Override //ok public boolean equals(Object obj) { return true; } @Mock DataLoader loader; //ok @SuppressWarnings("deprecation") DataLoader loader; //ok @SuppressWarnings("deprecation") public int foo() { return 1; } //ok @NotNull @Mock DataLoader loader; //ok
Use the following configuration to allow only one and only parameterized annotation on the same line:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="false"/> <property name="allowSamelineSingleParameterlessAnnotation" value="false"/> <property name="allowSamelineParameterizedAnnotation" value="true"/> </module>
Example to allow only one and only parameterized annotation on the same line:
@NotNull private boolean field1; //violation @Override public int hashCode() { return 1; } //violation @NotNull //ok private boolean field2; @Override //ok public boolean equals(Object obj) { return true; } @Mock DataLoader loader; //violation @SuppressWarnings("deprecation") DataLoader loader; //ok @SuppressWarnings("deprecation") public int foo() { return 1; } //ok @NotNull @Mock DataLoader loader; //violation
Use the following configuration to only validate annotations on methods to allow one single parameterless annotation on the same line:
<module name="AnnotationLocation"> <property name="tokens" value="METHOD_DEF"/> <property name="allowSamelineMultipleAnnotations" value="false"/> <property name="allowSamelineSingleParameterlessAnnotation" value="true"/> <property name="allowSamelineParameterizedAnnotation" value="false"/> </module>
Example for above configuration to check only methods:
@NotNull private boolean field1; //ok @Override public int hashCode() { return 1; } //ok @NotNull //ok private boolean field2; @Override //ok public boolean equals(Object obj) { return true; } @Mock DataLoader loader; //ok @SuppressWarnings("deprecation") DataLoader loader; //ok @SuppressWarnings("deprecation") public int foo() { return 1; } //violation @NotNull @Mock DataLoader loader; //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.annotation
Since Checkstyle 8.2
Checks that annotations are located on the same line with their targets. Verifying with this check is not good practice, but it is using by some style guides.
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens CLASS_DEF , INTERFACE_DEF , ENUM_DEF , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , PARAMETER_DEF , ANNOTATION_DEF , TYPECAST , LITERAL_THROWS , IMPLEMENTS_CLAUSE , TYPE_ARGUMENT , LITERAL_NEW , DOT , ANNOTATION_FIELD_DEF , RECORD_DEF , COMPACT_CTOR_DEF . | CLASS_DEF , INTERFACE_DEF , ENUM_DEF , METHOD_DEF , CTOR_DEF , VARIABLE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . | 8.2 |
To configure the check:
<module name="AnnotationOnSameLine"/>
Example:
class Foo { @SuppressWarnings("deprecation") // violation, annotation should be on the same line public Foo() { } @SuppressWarnings("unchecked") public void fun2() { // OK } } @SuppressWarnings("unchecked") class Bar extends Foo { // OK @Deprecated public Bar() { // OK } @Override // violation, annotation should be on the same line public void fun1() { } @Before @Override public void fun2() { // OK } @SuppressWarnings("deprecation") // violation, annotation should be on the same line @Before public void fun3() { } }
To configure the check to check for annotations applied on interfaces, variables and constructors:
<module name="AnnotationOnSameLine"> <property name="tokens" value="INTERFACE_DEF, VARIABLE_DEF, CTOR_DEF"/> </module>
Example:
@Deprecated interface Foo { // OK void doSomething(); } class Bar implements Foo { @SuppressWarnings("deprecation") // violation, annotation should be on the same line public Bar() { } @Override // OK public void doSomething() { } @Nullable // violation, annotation should be on the same line String s; }
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.annotation
Since Checkstyle 5.0
Checks the style of elements in annotations.
Annotations have three element styles starting with the least verbose.
ElementStyleOption.COMPACT_NO_ARRAY
ElementStyleOption.COMPACT
ElementStyleOption.EXPANDED
To not enforce an element style a ElementStyleOption.IGNORE
type is provided.
The desired style can be set through the elementStyle
property.
Using the ElementStyleOption.EXPANDED
style is more verbose.
The expanded version is sometimes referred to as "named parameters" in other languages.
Using the ElementStyleOption.COMPACT
style is less verbose.
This style can only be used when there is an element called 'value' which is either
the sole element or all other elements have default values.
Using the ElementStyleOption.COMPACT_NO_ARRAY
style is less verbose.
It is similar to the ElementStyleOption.COMPACT
style but single value arrays
are flagged.
With annotations a single value array does not need to be placed in an array initializer.
The ending parenthesis are optional when using annotations with no elements.
To always require ending parenthesis use the ClosingParensOption.ALWAYS
type.
To never have ending parenthesis use the ClosingParensOption.NEVER
type.
To not enforce a closing parenthesis preference a ClosingParensOption.IGNORE
type is provided. Set this through the closingParens
property.
Annotations also allow you to specify arrays of elements in a standard format.
As with normal arrays, a trailing comma is optional.
To always require a trailing comma use the TrailingArrayCommaOption.ALWAYS
type.
To never have a trailing comma use the TrailingArrayCommaOption.NEVER
type.
To not enforce a trailing array comma preference a
TrailingArrayCommaOption.IGNORE
type is provided.
Set this through the trailingArrayComma
property.
By default the ElementStyleOption
is set to COMPACT_NO_ARRAY
,
the TrailingArrayCommaOption
is set to NEVER
,
and the ClosingParensOption
is set to NEVER
.
According to the JLS, it is legal to include a trailing comma in arrays used in annotations but Sun's Java 5 & 6 compilers will not compile with this syntax. This may in be a bug in Sun's compilers since eclipse 3.4's built-in compiler does allow this syntax as defined in the JLS. Note: this was tested with compilers included with JDK versions 1.5.0.17 and 1.6.0.11 and the compiler included with eclipse 3.4.1.
name | description | type | default value | since |
---|---|---|---|---|
elementStyle | Define the annotation element styles. | ElementStyleOption |
compact_no_array
|
5.0 |
closingParens | Define the policy for ending parenthesis. | ClosingParensOption |
never
|
5.0 |
trailingArrayComma | Define the policy for trailing comma in arrays. | TrailingArrayCommaOption |
never
|
5.0 |
To configure the check:
<module name="AnnotationUseStyle"/>
Example:
@Deprecated // OK @SomeArrays(pooches={DOGS.LEO}) // Violation - COMPACT_NO_ARRAY @SuppressWarnings({""}) // Violation - COMPACT_NO_ARRAY public class TestOne { } @SomeArrays(pooches={DOGS.LEO}, um={}, test={"bleh"}) // Violation - COMPACT_NO_ARRAY @SuppressWarnings("") // OK @Deprecated() // Violation - cannot have closing parenthesis class TestTwo { }
To configure the check to enforce an expanded
style,
with a trailing array comma set to never
and always including the closing parenthesis.
<module name="AnnotationUseStyle"> <property name="elementStyle" value="expanded"/> <property name="trailingArrayComma" value="never"/> <property name="closingParens" value="always"/> </module>
Example:
@Deprecated // Violation - must have closing parenthesis @SomeArrays(pooches={DOGS.LEO}) // OK @SuppressWarnings({""}) // Violation - EXPANDED public class TestOne { } @SomeArrays(pooches={DOGS.LEO}, um={}, test={"bleh"}) // OK @SuppressWarnings("") // Violation - EXPANDED @Deprecated() // OK class TestTwo { }
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.annotation
Since Checkstyle 5.0
Verifies that the annotation @Deprecated
and the Javadoc tag
@deprecated
are both present when either of them is present.
Both ways of flagging deprecation serve their own purpose. The @Deprecated annotation is used for compilers and development tools. The @deprecated javadoc tag is used to document why something is deprecated and what, if any, alternatives exist.
In order to properly mark something as deprecated both forms of deprecation should be present.
Package deprecation is a exception to the rule of always using the javadoc tag and annotation to deprecate. It is not clear if the javadoc tool will support it or not as newer versions keep flip flopping on if it is supported or will cause an error. See JDK-8160601. The deprecated javadoc tag is currently the only way to say why the package is deprecated and what to use instead. Until this is resolved, if you don't want to print violations on package-info, you can use a filter to ignore these files until the javadoc tool faithfully supports it. An example config using SuppressionSingleFilter is:
<!-- required till https://bugs.openjdk.java.net/browse/JDK-8160601 --> <module name="SuppressionSingleFilter"> <property name="checks" value="MissingDeprecatedCheck"/> <property name="files" value="package-info\.java"/> </module>
name | description | type | default value | since |
---|---|---|---|---|
violateExecutionOnNonTightHtml | Control when to print violations if the Javadoc being examined by this check violates the tight html rules defined at Tight-HTML Rules. | boolean | false |
8.24 |
To configure the check:
<module name="MissingDeprecated"/>
Examples of validating source code:
@Deprecated public static final int MY_CONST = 123456; // no violation /** This javadoc is missing deprecated tag. */ @Deprecated public static final int COUNTER = 10; // 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.annotation
Since Checkstyle 5.0
Verifies that the @Override
annotation is present
when the @inheritDoc
javadoc tag is present.
Rationale: The @Override annotation helps compiler tools ensure that an override is actually occurring. It is quite easy to accidentally overload a method or hide a static method and using the @Override annotation points out these problems.
This check will log a violation if using the @inheritDoc tag on a method that is not valid (ex: private, or static method).
There is a slight difference between the @Override annotation in Java 5 versus Java 6 and above. In Java 5, any method overridden from an interface cannot be annotated with @Override. In Java 6 this behavior is allowed.
As a result of the aforementioned difference between Java 5 and Java 6, a
property called javaFiveCompatibility
is available. This
property will only check classes, interfaces, etc. that do not contain the
extends or implements keyword or are not anonymous classes. This means it
only checks methods overridden from java.lang.Object
.
Java 5 Compatibility mode severely limits this check. It is recommended to
only use it on Java 5 source.
name | description | type | default value | since |
---|---|---|---|---|
javaFiveCompatibility | Enable java 5 compatibility mode. | boolean |
false
|
5.0 |
To configure the check:
<module name="MissingOverride"/>
Example:
class Test extends SuperClass { /** {@inheritDoc} */ @Override public void test1() { // OK } /** {@inheritDoc} */ public void test2() { // violation, should be annotated with @Override } /** {@inheritDoc} */ private void test3() { // violation, using the @inheritDoc tag on private method } /** {@inheritDoc} */ public static void test4() { // violation, using the @inheritDoc tag on static method } }
To configure the check for the javaFiveCompatibility
mode:
<module name="MissingOverride"> <property name="javaFiveCompatibility" value="true"/> </module>
Example:
class Test1 { /** {@inheritDoc} */ public void equals() { // violation, should be annotated with @Override } } interface Test2 { /** {@inheritDoc} */ void test(); // violation, should be annotated with @Override } class Test3 extends SuperClass { /** {@inheritDoc} */ public void test() { // OK, is ignored because class extends other class } } class Test4 implements SuperInterface { /** {@inheritDoc} */ public void test() { // OK, is ignored because class implements interface } } class Test5 { Runnable r = new Runnable() { /** {@inheritDoc} */ public void run() { // OK, is ignored because class is anonymous class } }; }
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.annotation
Since Checkstyle 5.0
Checks that all package annotations are in the package-info.java file.
For Java SE8 and above, placement of package annotations in the package-info.java file is enforced by the compiler and this check is not necessary.
For Java SE7 and below, the Java Language Specification highly recommends but doesn't require that annotations are placed in the package-info.java file, and this check can help to enforce that placement.
See Java Language Specification, §7.4.1 for more info.
To configure the check:
<module name="PackageAnnotation"/>
Example of validating MyClass.java:
@Deprecated package com.example.annotations.packageannotation; //violation
Example of fixing violation in MyClass.java:
package com.example.annotations.packageannotation; //ok
Example of validating package-info.java:
@Deprecated package com.example.annotations.packageannotation; //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.annotation
Since Checkstyle 5.0
Allows to specify what warnings that @SuppressWarnings
is not allowed to suppress.
You can also specify a list of TokenTypes that
the configured warning(s) cannot be suppressed on.
Limitations: This check does not consider conditionals inside the @SuppressWarnings annotation.
For example:
@SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")
.
According to the above example, the "unused" warning is being suppressed
not the "unchecked" or "foo" warnings. All of these warnings will be
considered and matched against regardless of what the conditional
evaluates to.
The check also does not support code like @SuppressWarnings("un" + "used")
,
@SuppressWarnings((String) "unused")
or
@SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})
.
By default, any warning specified will be disallowed on all legal TokenTypes unless otherwise specified via the tokens property.
Also, by default warnings that are empty strings or all whitespace (regex: ^$|^\s+$) are flagged. By specifying, the format property these defaults no longer apply.
This check can be configured so that the "unchecked" and "unused" warnings cannot be suppressed on anything but variable and parameter declarations. See below of an example.
name | description | type | default value | since |
---|---|---|---|---|
format | Specify the RegExp to match against warnings. Any warning being suppressed matching this pattern will be flagged. | Pattern |
"^\s*+$"
|
5.0 |
tokens | tokens to check | subset of tokens CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , ANNOTATION_FIELD_DEF , ENUM_CONSTANT_DEF , PARAMETER_DEF , VARIABLE_DEF , METHOD_DEF , CTOR_DEF , COMPACT_CTOR_DEF , RECORD_DEF . | CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , ANNOTATION_FIELD_DEF , ENUM_CONSTANT_DEF , PARAMETER_DEF , VARIABLE_DEF , METHOD_DEF , CTOR_DEF , COMPACT_CTOR_DEF , RECORD_DEF . | 5.0 |
To configure the check:
<module name="SuppressWarnings"/>
To configure the check so that the "unchecked" and "unused" warnings cannot be suppressed on anything but variable and parameter declarations.
<module name="SuppressWarnings"> <property name="format" value="^unchecked$|^unused$"/> <property name="tokens" value=" CLASS_DEF,INTERFACE_DEF,ENUM_DEF, ANNOTATION_DEF,ANNOTATION_FIELD_DEF, ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF "/> </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.annotation
Since Checkstyle 5.7
Maintains a set of check suppressions from
@SuppressWarnings
annotations. It allows to
prevent Checkstyle from reporting violations from parts of code
that were annotated with @SuppressWarnings
and
using name of the check to be excluded. You can also define
aliases for check names that need to be suppressed.
name | description | type | default value | since |
---|---|---|---|---|
aliasList |
Specify aliases for check names that can be used in code within
SuppressWarnings .
|
String[] in a format of comma separated attribute=value entries. The attribute is the fully qualified name of the Check and value is its alias. | null |
5.7 |
To prevent FooCheck
violations from being reported write:
@SuppressWarnings("foo") interface I { } @SuppressWarnings("foo") enum E { } @SuppressWarnings("foo") InputSuppressWarningsFilter() { }
Some real check examples:
This will prevent from invocation of the MemberNameCheck:
@SuppressWarnings({"membername"}) private int J;
You can also use a checkstyle
prefix to prevent compiler from
processing this annotations.
For example this will prevent ConstantNameCheck:
@SuppressWarnings("checkstyle:constantname") private static final int m = 0;
The general rule is that the argument of the @SuppressWarnings
will be
matched against class name of the checker in lower case and without Check
suffix if present.
If aliasList
property was provided you can use your own names e.g below
code will work if there was provided a ParameterNumberCheck=paramnum
in
the aliasList
:
@SuppressWarnings("paramnum") public void needsLotsOfParameters(@SuppressWarnings("unused") int a, int b, int c, int d, int e, int f, int g, int h) { ... }
It is possible to suppress all the checkstyle warnings with the argument
"all"
:
@SuppressWarnings("all") public void someFunctionWithInvalidStyle() { //... }
com.puppycrawl.tools.checkstyle.checks