Java 使用 @SuppressWarnings 注释忽略 Checkstyle 警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27688426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:51:21  来源:igfitidea点击:

Ignoring of Checkstyle warnings with annotation @SuppressWarnings

javaeclipsecheckstyle

提问by Mark

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

我尝试通过带有注释的 checkstyle 忽略或禁用 eclipse 中的一些无用警告,@SuppressWarnings例如 How to disable a specific checkstyle rule for a specific line of code?

but this don't work for me.

但这对我不起作用。

Here is the checkstyle.xml

这是 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:

这里是java代码:

@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.

也将warning 的值设置为“all”@SuppressWarnings("all")或者@SuppressWarnings("CyclomaticComplexity")@SuppressWarnings("cyclomaticcomplexity")没有任何结果。

The documentation of checkstyle is poor. Some ideas?

checkstyle 的文档很差。一些想法?

回答by Stefan

A. SuppressWarnings Filter

A. SuppressWarnings 过滤器

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

使用 checkstyle 6.5.0 我可以使用 @SuppressWarnings。请考虑以下几点:

  • The SuppressWarnings filter has to be enabledin 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.
  • Optionallya 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.
  • 必须在 Checkstyle 设置中启用SuppressWarnings 过滤器(请参阅下面示例设置中的“TreeWalker”)。
  • 在 SuppressWarnings 注释的标签中,您必须使用所有小写的 checkstyle 模块的名称。
  • 可选一个前缀“的CheckStyle:”可以在标签中使用。
  • 如果注释没有按预期工作,请尝试更改其位置。MagicNumber 模块的注解需要放在方法之前。某些注释必须直接位于显示问题的位置,而其他注释必须位于类定义的前面。

Some examples for the checkstyle module "MagicNumber":

checkstyle 模块“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 suppresswarningswhich 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 messagethat 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:anoninnerlengthto 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.)

  • 我在 Eclipse 首选项中使用 Java=>Compiler=>Errors/Warnings=>Annotations=>Unhandled token in '@SuppressWarnings'' 中禁用了一个警告不支持的抑制警告:忽略

  • 将鼠标悬停在代码问题上时弹出的违规消息不会显示相应 checkstyle 模块的名称(在 xml 文件中定义)。我启用了选项“在违规消息中包含模块 ID(如果可用)”并手动将所有模块 ID 更改为与 xml 文件中的相应模块名称相同,但要小写。例如,有一个模块 <name="AnonInnerLength"> 在 Eclipse checkstyle 设置中显示为“匿名内部类长度”。该模块没有模块 ID。我将模块 id 更改为checkstyle:anoninnerlength以使我的同事更容易抑制警告:

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

  • 我在模块 id 和 SuppressWarnings 标签中使用前缀“checkstyle:”来明确警告不是“标准 Eclipse 警告”。(可选前缀“checkstyle:”已经可以在标签中使用而无需更改模块 id。但是,该前缀不会显示在违规消息中。将其包含在模块 id 中会使消息更加透明,并激励我的同事在标签中也包括前缀。)

B. Suppression Comment Filter

B. 抑制评论过滤器

  • 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.
  • checkstyle 过滤器 Filters=>Suppression Comment Filter 使用在 xml 文件中指定的模块名称。
  • 如果使用前缀“checkstyle:”,模块名称也可以使用小写。

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:

C. 示例 checkstyle settings.xml 文件:

 <?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="TreeWalker">
    <property name="tabWidth" value="4"/>
    <module name="FileContentsHolder"/>
    <module name="SuppressWarningsHolder"/>

    <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 name="SuppressWarnings">
      <property name="id" value="checkstyle:suppresswarnings"/>
    </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 name="SuppressWithNearbyCommentFilter"/>

  <module name="SuppressWarningsFilter"/>

  <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=""/>
  </module>

</module>

回答by Max Peng

My checkstyle version is 8.1.

我的 checkstyle 版本是8.1.

It works with gradle config like this:

它可以像这样使用 gradle 配置:

build.gradle:

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.

注意:前缀checkstyle:是可选的。希望这可以帮助某人。

回答by sschmeck

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

只是为了强调 Caio Faustino 的评论,它至少解决了 checkstyle 8.19 的问题。

  1. Add <module name="SuppressWarningsHolder"/>to the Treewalkerelement.
  2. Add <module name="SuppressWarningsFilter"/>as general module.
  1. 添加<module name="SuppressWarningsHolder"/>Treewalker元素。
  2. 添加<module name="SuppressWarningsFilter"/>为通用模块。
<module name="Checker">
  <--! ... -->
  <module name="TreeWalker">
    <--! ... -->
    <module name="SuppressWarningsHolder"/>
  </module>
  <module name="SuppressWarningsFilter"/>
</module>