Ignoring of Checkstyle warnings with annotation @SuppressWarnings

91,813

Solution 1

A. SuppressWarnings Filter

With checkstyle 6.5.0 I can use @SuppressWarnings. Please consider following points:

  • The SuppressWarnings filter has to be enabled in the Checkstyle settings (see "TreeWalker" in the example settings below).
  • In the tag for the SuppressWarnings annotation you have to use the name of the checkstyle module in all lower case.
  • Optionally a prefix "checkstyle:" can be used in the tag.
  • If the annotation does not work as expected try to change its position. The annotation for the MagicNumber module needs to be put before the method. Some annotations have to be located directly where the issue is shown and others have to be located in front of the class definition.

Some examples for the checkstyle module MagicNumber:

Works:

@SuppressWarnings("checkstyle:magicnumber")
public example(){
    int g = 5;
}

.

@SuppressWarnings("magicnumber")
public example(){
    int g = 5;
}

Does not work:

@SuppressWarnings("MagicNumber")
public example(){
    int g = 5;
}

.

@SuppressWarnings("magicNumber")
public example(){        
    int g = 5;
}

.

public example(){
    @SuppressWarnings("magicnumber")
    int g = 5;
}

Further notes

  • I got a warning unsupported suppresswarnings which I disabled in the Eclipse preferences with Java=>Compiler=>Errors/Warnings=>Annotations=>Unhandled token in @SuppressWarnings: Ignore

  • The name (as defined in the xml file) of the corresponding checkstyle module is not shown in the violation message that pops up when hovering over a code issue. I enabled the option "include module id (if available) in violation message" and manually altered all module ids to be the same as the corresponding module name in the xml file, but lower case. For example there is a module <name="AnonInnerLength"> which is displayed in the Eclipse checkstyle settings as "Anonymous inner classes length". That module had no module id. I changed the module id to checkstyle:anoninnerlength to make it easier for my colleagues to suppress the warning:

    <module name="AnonInnerLength">
    <property name="id" value="checkstyle:anoninnerlength"/>
    <module>

  • I use the prefix "checkstyle:" in the module id as well as in the SuppressWarnings tag to make it explicit that the warning is not a "standard Eclipse warning". (The optional prefix "checkstyle:" could already be used in the tag without altering the module id. However, the prefix would not be shown in the violation message. Including it in the module id makes the message more transparent and motivates my colleagues to include the prefix in the tag, too.)

B. Suppression Comment Filter

  • The checkstyle filter Filters=>Suppression Comment Filter uses the module name as it is specified in the xml file.
  • If you use the prefix "checkstyle:", the module name can also be used in lower case.

Works:

//CHECKSTYLE:OFF: checkstyle:magicnumber        
public example(){
    int g = 5;
}   
//CHECKSTYLE:ON: checkstyle:magicnumber

.

//CHECKSTYLE:OFF: MagicNumber           
public example(){
    int g = 5;
}   
//CHECKSTYLE:ON: MagicNumber

Does not work:

//CHECKSTYLE:OFF: magicnumber           
public example(){
    int g = 5;
}   
//CHECKSTYLE:ON: magicnumber

C. Example checkstyle settings.xml file:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">


<!--
    Checkstyle-Configuration with module ids that can be used as    
    tags in @SuppressWarnings
-->

<module name="Checker">

  <property name="severity" value="warning"/>

  <module name="SuppressWarningsFilter"/>
  
  <module name="TreeWalker">
    <property name="tabWidth" value="4"/>
    <module name="FileContentsHolder"/>
    <module name="SuppressWarningsHolder"/>

    <module name="SuppressWarnings">
      <property name="id" value="checkstyle:suppresswarnings"/>
    </module> 

    <module name="SuppressWithNearbyCommentFilter"/>

     
  
    <module name="SuppressionCommentFilter">
      <metadata name="net.sf.eclipsecs.core.comment" value="Single warning"/>
      <property name="offCommentFormat" value="CHECKSTYLE\:OFF\: ([\w\|]+)"/>
      <property name="onCommentFormat" value="CHECKSTYLE\:ON\: ([\w\|]+)"/>
      <property name="checkFormat" value="$1"/>
    </module>
    
    <module name="JavadocMethod">
      <property name="id" value="checkstyle:javadocmethod"/>   
      <property name="severity" value="ignore"/>
      <property name="allowMissingParamTags" value="true"/>
      <property name="allowMissingThrowsTags" value="true"/>
      <property name="allowMissingReturnTag" value="true"/>
      <property name="suppressLoadErrors" value="true"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="JavadocType">
      <property name="id" value="checkstyle:javadoctype"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="JavadocVariable">
      <property name="id" value="checkstyle:javadocvariable"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="JavadocStyle">
      <property name="id" value="checkstyle:javadocstyle"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="ConstantName">
      <property name="id" value="checkstyle:constantname"/>
    </module>
    
    <module name="LocalFinalVariableName">
      <property name="id" value="checkstyle:localfinalvariablename"/>
    </module>
    
    <module name="LocalVariableName">
      <property name="id" value="checkstyle:localvariablename"/>
    </module>
    
    <module name="MemberName">
      <property name="id" value="checkstyle:membername"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="MethodName">
      <property name="id" value="checkstyle:methodname"/>
    </module>
    
    <module name="PackageName">
      <property name="id" value="checkstyle:packagename"/>
    </module>
    
    <module name="ParameterName">
      <property name="id" value="checkstyle:parametername"/>
    </module>
    
    <module name="StaticVariableName">
      <property name="id" value="checkstyle:staticvariablename"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="TypeName">
      <property name="id" value="checkstyle:typename"/>
    </module>
    
    <module name="AvoidStarImport">
      <property name="id" value="checkstyle:avoidstarimport"/>
    </module>
    
    <module name="IllegalImport">
      <property name="id" value="checkstyle:illegalimport"/>
    </module>
    
    <module name="RedundantImport">
      <property name="id" value="checkstyle:redundantimport"/>
    </module>
    
    <module name="UnusedImports">
      <property name="id" value="checkstyle:unusedimports"/>
    </module>
    
    <module name="ParameterNumber">
      <property name="id" value="checkstyle:parameternumber"/>
    </module>
    
    <module name="EmptyForIteratorPad">
      <property name="id" value="checkstyle:emptyforiteratorpad"/>
    </module>
    
    <module name="MethodParamPad">
      <property name="id" value="checkstyle:methodparampad"/>
    </module>
    
    <module name="NoWhitespaceAfter">
      <property name="id" value="checkstyle:nowhitespaceafter"/>
      <property name="tokens" value="BNOT,DEC,DOT,INC,LNOT,UNARY_MINUS,UNARY_PLUS"/>
    </module>
    
    <module name="NoWhitespaceBefore">
      <property name="id" value="checkstyle:nowhitespacebefore"/>
    </module>
    
    <module name="OperatorWrap">
      <property name="id" value="checkstyle:operatorwrap"/>
      <property name="option" value="eol"/>
    </module>
    
    <module name="ParenPad">
      <property name="id" value="checkstyle:parenpad"/>
    </module>
    
    <module name="TypecastParenPad">
      <property name="id" value="checkstyle:typecastparenpad"/>
    </module>
    
    <module name="WhitespaceAfter">
      <property name="id" value="checkstyle:whitespaceafter"/>
    </module>
    
    <module name="WhitespaceAround">
      <property name="id" value="checkstyle:whitespacearound"/>
    </module>
    
    <module name="ModifierOrder">
      <property name="id" value="checkstyle:modifierorder"/>
    </module>
    
    <module name="RedundantModifier">
      <property name="id" value="checkstyle:redundantmodifier"/>
    </module>
    
    <module name="LeftCurly">
      <property name="id" value="checkstyle:leftcurly"/>
    </module>
    
    <module name="NeedBraces">
      <property name="id" value="checkstyle:needbraces"/>
    </module>
    
    <module name="RightCurly">
      <property name="id" value="checkstyle:rightcurly"/>
    </module>
    
    <module name="AvoidInlineConditionals">
      <property name="id" value="checkstyle:avoidinlineconditionals"/>
    </module>
    
    <module name="EmptyStatement">
      <property name="id" value="checkstyle:emptystatement"/>
    </module>
    
    <module name="HiddenField">
      <property name="id" value="checkstyle:hiddenfield"/>
      <property name="tokens" value="VARIABLE_DEF"/>
    </module>
    
    <module name="IllegalInstantiation">
      <property name="id" value="checkstyle:illegalinstantiation"/>
    </module>
    
    <module name="InnerAssignment">
      <property name="id" value="checkstyle:innerassignment"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="MagicNumber">
      <property name="id" value="checkstyle:magicnumber"/>
    </module>
    
    <module name="MissingSwitchDefault">
      <property name="id" value="checkstyle:missingswitchdefault"/>
    </module>
    
    <module name="RedundantThrows">
      <property name="id" value="checkstyle:redundantthrows"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="SimplifyBooleanExpression">
      <property name="id" value="checkstyle:simplifybooleanexpression"/>
    </module>
    
    <module name="SimplifyBooleanReturn">
      <property name="id" value="checkstyle:simplifybooleanreturn"/>
    </module>
    
    <module name="DesignForExtension">
      <property name="id" value="checkstyle:designforextension"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="FinalClass">
      <property name="id" value="checkstyle:finalclass"/>
    </module>
    
    <module name="HideUtilityClassConstructor">
      <property name="id" value="checkstyle:hideutilityclassconstructor"/>
    </module>
    
    <module name="VisibilityModifier">
      <property name="id" value="checkstyle:visibilitymodifier"/>
    </module>
    
    <module name="ArrayTypeStyle">
      <property name="id" value="checkstyle:arraytypestyle"/>
    </module>
    
    <module name="UpperEll">
      <property name="id" value="checkstyle:upperell"/>
    </module>
    
    <module name="AnnotationUseStyle">
      <property name="id" value="checkstyle:annotationusestyle"/>
    </module>
    
    <module name="MissingDeprecated">
      <property name="id" value="checkstyle:missingdeprecated"/>
    </module>
    
    <module name="MissingOverride">
      <property name="id" value="checkstyle:missingoverride"/>
    </module>
    
    <module name="PackageAnnotation">
      <property name="id" value="checkstyle:packageannotation"/>
    </module>
    
    <module name="AbstractClassName">
      <property name="id" value="checkstyle:abstractclassname"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="AnonInnerLength">
      <property name="id" value="checkstyle:anoninnerlength"/>     
    </module>
    
    <module name="ExecutableStatementCount">
      <property name="id" value="checkstyle:executablestatementcount"/>
      <property name="max" value="20"/>
      <property name="tokens" value="INSTANCE_INIT,STATIC_INIT,METHOD_DEF,CTOR_DEF"/>
    </module>
    
    <module name="LineLength">
      <property name="id" value="checkstyle:linelength"/>
      <property name="max" value="120"/>
      <property name="tabWidth" value="4"/>
    </module>
        
    <module name="MethodLength">
      <property name="id" value="checkstyle:methodlength"/>
      <property name="severity" value="ignore"/>
      <property name="max" value="20"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="OuterTypeNumber">
      <property name="id" value="checkstyle:outertypenumber"/>
    </module>
    
    <module name="RegexpSinglelineJava">
      <property name="id" value="checkstyle:regexpsinglelinejava"/>
      <property name="format" value="^.*System.out.println.*$"/>
      <property name="ignoreComments" value="true"/>
    </module>
    
    <module name="AvoidNestedBlocks">
      <property name="id" value="checkstyle:avoidnestedblocks"/>
      <property name="allowInSwitchCase" value="true"/>
    </module>
    
    <module name="CovariantEquals">
      <property name="id" value="checkstyle:covariantequals"/>
    </module>
    
    <module name="DefaultComesLast">
      <property name="id" value="checkstyle:defaultcomeslast"/>
    </module>
    
    <module name="DeclarationOrder">
      <property name="id" value="checkstyle:declarationorder"/>
    </module>
    
    <module name="EqualsHashCode">
      <property name="id" value="checkstyle:equalshashcode"/>
    </module>
    
    <module name="ExplicitInitialization">
      <property name="id" value="checkstyle:explicitinitialization"/>
    </module>
    
    <module name="FallThrough">
      <property name="id" value="checkstyle:fallthrough"/>
    </module>
    
    <module name="IllegalCatch">
      <property name="id" value="checkstyle:illegalcatch"/>
    </module>
    
    <module name="IllegalThrows">
      <property name="id" value="checkstyle:illegalthrows"/>
    </module>
    
    <module name="MissingCtor">
      <property name="id" value="checkstyle:missingctor"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="ModifiedControlVariable">
      <property name="id" value="checkstyle:modifiedcontrolvariable"/>
    </module>
    
    <module name="MultipleStringLiterals">
      <property name="id" value="checkstyle:multiplestringliterals"/>
       <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="MultipleVariableDeclarations">
      <property name="id" value="checkstyle:multiplevariabledeclarations"/>
    </module>
    
    <module name="NestedForDepth">
      <property name="id" value="checkstyle:nestedfordepth"/>
      <property name="max" value="2"/>
    </module>
    
    <module name="NestedIfDepth">
      <property name="id" value="checkstyle:nestedifdepth"/>
      <property name="max" value="2"/>
    </module>
    
    <module name="NestedTryDepth">
      <property name="id" value="checkstyle:nestedtrydepth"/>
    </module>
    
    <module name="NoClone">
      <property name="id" value="checkstyle:noclone"/>
    </module>
    
    <module name="NoFinalizer">
      <property name="id" value="checkstyle:nofinalizer"/>
    </module>
    
    <module name="ParameterAssignment">
      <property name="id" value="checkstyle:parameterassignment"/>
    </module>
    
    <module name="StringLiteralEquality">
      <property name="id" value="checkstyle:stringliteralequality"/>
    </module>
    
    <module name="OneStatementPerLine">
      <property name="id" value="checkstyle:onestatementperline"/>
    </module>
    
    <module name="InnerTypeLast">
      <property name="id" value="checkstyle:innertypelast"/>
    </module>
    
    <module name="InterfaceIsType">
      <property name="id" value="checkstyle:interfaceistype"/>
    </module>
    
    <module name="MutableException">
      <property name="id" value="checkstyle:mutableexception"/>
    </module>
    
    <module name="BooleanExpressionComplexity">
      <property name="id" value="checkstyle:booleanexpressioncomplexity"/>
    </module>
    
    <module name="ClassFanOutComplexity">
      <property name="id" value="checkstyle:classfanoutcomplexity"/>
      <property name="max" value="10"/>
    </module>
    
    <module name="JavaNCSS">
      <property name="id" value="checkstyle:gavancss"/>
      <property name="methodMaximum" value="20"/>
    </module>
    
    <module name="NPathComplexity">
      <property name="id" value="checkstyle:npathcomplexity"/>
      <property name="max" value="1200"/>
    </module>
    
    <module name="TrailingComment">
      <property name="id" value="checkstyle:trailingcomment"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    <module name="UncommentedMain">
      <property name="id" value="checkstyle:uncommentedmain"/>
    </module>
    
    <module name="CyclomaticComplexity">
      <property name="id" value="checkstyle:cyclomaticcomplexity"/>
      <property name="max" value="7"/>
    </module>
    
    <module name="StrictDuplicateCode">
      <property name="id" value="checkstyle:strictduplicatecode"/>
      <property name="severity" value="ignore"/>
      <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
    </module>
    
    
    
  </module>
  
  
  
  <module name="JavadocPackage">
    <property name="id" value="checkstyle:javadocpackage"/>
    <property name="severity" value="ignore"/>
    <metadata name="net.sf.eclipsecs.core.lastEnabledSeverity" value="inherit"/>
  </module>
  
  <module name="Translation">
      <property name="id" value="checkstyle:translation"/>
  </module>
  
  <module name="FileLength">
    <property name="id" value="checkstyle:filelength"/>   
    <property name="max" value="1000"/>
  </module>
  
  <module name="NewlineAtEndOfFile"> 
    <property name="id" value="checkstyle:newlineatendoffile"/>   
    <property name="fileExtensions" value="*.java"/>
  </module>
  
  
  
</module>

Solution 2

Just to emphasize the comment of Caio Faustino which fixes the problem at least for checkstyle 8.19.

  1. Add <module name="SuppressWarningsHolder"/> to the Treewalker element.
  2. Add <module name="SuppressWarningsFilter"/> as general module.
<module name="Checker">
  <--! ... -->
  <module name="TreeWalker">
    <--! ... -->
    <module name="SuppressWarningsHolder"/>
  </module>
  <module name="SuppressWarningsFilter"/>
</module>

Solution 3

My checkstyle version is 8.1.

It works with gradle config like this:

build.gradle:

apply plugin: 'checkstyle'

checkstyle {
    configFile = file('config/checkstyle.xml')
    toolVersion = '8.1'
}

And ignore magic number like this:

@SuppressWarnings("checkstyle:MagicNumber")
private String f(String a) {
    String b = a.substring(0, 7);
    String c = a.substring(a.length() - 3);
    return b + "-" + c;
}

NOTE: prefix checkstyle: is optional. Hope this can help someone.

Share:
91,813
Mark
Author by

Mark

Most of the people out there like their computers because they help them solving problems. We - programmers - love them because they are. [Linus Torvalds] Entwicklung - Schulung - Beratung GULP-Profile

Updated on October 16, 2020

Comments

  • Mark
    Mark over 3 years

    I try to ignore or disable some useless warnings in eclipse by checkstyle with annotation @SuppressWarnings like How to disable a particular checkstyle rule for a particular line of code?

    but this don't work for me.

    Here is the checkstyle.xml

    <module name="Checker">
      <property name="severity" value="warning"/>
      <module name="SuppressWarningsFilter"/>
      <module name="TreeWalker">
        <property name="tabWidth" value="4"/>
        <module name="FileContentsHolder"/>
        <module name="SuppressWarningsHolder"/>
        <module name="CyclomaticComplexity"/>
        ...
    

    and here the java code:

    @SuppressWarnings("checkstyle:CyclomaticComplexity")
    public void doSomeThing() {
     ...
    }
    

    Also set the value of warning to "all" @SuppressWarnings("all") or @SuppressWarnings("CyclomaticComplexity"), @SuppressWarnings("cyclomaticcomplexity") is without any result.

    The documentation of checkstyle is poor. Some ideas?

  • Justin Tilson
    Justin Tilson about 6 years
    would you be willing to share your checkstyle.xml file?
  • Max Peng
    Max Peng about 6 years
  • Justin Tilson
    Justin Tilson about 6 years
    Something must be off in my environment. I've copied your configs verbatim and my suppressions are still being ignored. I'm using checkstyle 8.1, and Gradle 4.4.1. At the start of each error, I see: [ant:checkstyle] [ERROR]... I'm not sure how ant is playing into this or if that is an issue at all. Is your code in a publicly accessible repo anywhere? Could I clone it and try to run it?
  • Neeraj
    Neeraj almost 6 years
    As verified in Checkstyle 8.1, there is no longer a need for the name of the checkstyle module to be in lowercase.
  • Caio Faustino
    Caio Faustino over 5 years
    From what I understood, the SuppressWarnings annotation only worked after I added <module name="SuppressWarningsHolder"/> inside the TreeWalker. Not sure if necessary but I also added <module name="SuppressWarningsFilter"/> outside the TreeWalker.
  • Michael Coxon
    Michael Coxon about 5 years
    I can confirm that the only thing that would work was the use of <module name="SuppressWarningsFilter"/> outside the TreeWalker - this was or checkstyle 8.9
  • granadaCoder
    granadaCoder over 3 years
    #blessYou. I'v been all over the internet trying to figure out why my 8.33 wasn't working. Thanks for the "context" of the 2 magic xml-elmements.
  • Marco Martins
    Marco Martins about 3 years
    Without making any other changes in files the only thing that worked for me was the comment to turn off and on //CHECKSTYLE:OFF: StaticVariableName //CHECKSTYLE:ON: StaticVariableName, so ended up using this approach.