Java 如何禁用特定代码行的特定 checkstyle 规则?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4023185/
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-14 08:35:23  来源:igfitidea点击:

How to disable a particular checkstyle rule for a particular line of code?

javacheckstyle

提问by yegor256

I have a checkstylevalidation rule configured in my project, that prohibits to define class methods with more than 3 input parameters. The rule works fine for myclasses, but sometimes I have to extend third-party classes, which do not obey this particular rule.

我在我的项目中配置了一个checkstyle验证规则,该规则禁止定义具有超过 3 个输入参数的类方法。该规则适用于我的类,但有时我必须扩展不遵守此特定规则的第三方类。

Is there a possibility to instruct "checkstyle" that a certain method should be silently ignored?

是否有可能指示“checkstyle”应该默默地忽略某个方法?

BTW, I ended up with my own wrapper of checkstyle: qulice.com(see Strict Control of Java Code Quality)

顺便说一句,我最终得到了自己的 checkstyle 包装器:qulice.com(请参阅Java 代码质量的严格控制

采纳答案by Chris Knight

Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml

http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter查看 supressionCommentFilter 的使用。您需要将该模块添加到您的 checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

它是可配置的。因此,您可以在代码中添加注释以关闭 checkstyle(在各个级别),然后通过在代码中使用注释重新打开。例如

//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON

Or even better, use this more tweaked version:

或者更好的是,使用这个经过调整的版本:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value=""/>
</module>

which allows you to turn off specific checks for specific lines of code:

它允许您关闭对特定代码行的特定检查:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

*Note: you'll also have to add the FileContentsHolder:

*注意:您还必须添加FileContentsHolder

<module name="FileContentsHolder"/>

See also

也可以看看

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>
</module>

under the SuppressionFiltersection on that same page, which allows you to turn off individual checks for pattern matched resources.

SuppressionFilter同一页面上的部分下,它允许您关闭对模式匹配资源的单独检查。

So, if you have in your checkstyle.xml:

因此,如果您在 checkstyle.xml 中有:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>
</module>

You can turn it off in your suppression xml file with:

您可以使用以下命令在抑制 xml 文件中将其关闭:

<suppress id="maxParameterNumber" files="YourCode.java"/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarningsjava annotation. To do this, you will need to add two new modules (SuppressWarningsFilterand SuppressWarningsHolder) in your configuration file:

现在在 Checkstyle 5.7 中可用的另一种方法是通过@SuppressWarningsjava 注释抑制违规。为此,您需要在配置文件中添加两个新模块(SuppressWarningsFilterSuppressWarningsHolder):

<module name="Checker">
   ...
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       ...
       <module name="SuppressWarningsHolder" />
   </module>
</module> 

Then, within your code you can do the following:

然后,在您的代码中,您可以执行以下操作:

@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {

or, for multiple suppressions:

或者,对于多次抑制:

@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {

NB:The "checkstyle:" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.

注意:checkstyle:”前缀是可选的(但推荐)。根据文档,参数名称必须全部小写,但实践表明任何情况都有效。

回答by Akos Cz

What also works well is the SuppressWithNearbyCommentFilterwhich uses individual comments to suppress audit events.

同样有效的是SuppressWithNearbyCommentFilter,它使用单个注释来抑制审计事件。

For example

例如

// CHECKSTYLE IGNORE check FOR NEXT 1 LINES
public void onClick(View view) { ... }

To configure a filter so that CHECKSTYLE IGNORE check FOR NEXT var LINES avoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):

配置过滤器,以便CHECKSTYLE IGNORE check FOR NEXT var LINES 避免触发对当前行和下一个var 行(总共var+1 行)的给定检查的任何审计:

<module name="SuppressWithNearbyCommentFilter">
    <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/>
    <property name="checkFormat" value=""/>
    <property name="influenceFormat" value=""/>
</module>

http://checkstyle.sourceforge.net/config.html

http://checkstyle.sourceforge.net/config.html

回答by Henrik Heimbuerger

If you prefer to use annotations to selectively silence rules, this is now possible using the @SuppressWarningsannotation, starting with Checkstyle 5.7 (and supported by the Checkstyle Maven Plugin 2.12+).

如果您更喜欢使用注释来选择性地使规则静音,现在可以使用@SuppressWarnings注释,从 Checkstyle 5.7 开始(并由 Checkstyle Maven 插件 2.12+ 支持)。

First, in your checkstyle.xml, add the SuppressWarningsHoldermodule to the TreeWalker:

首先,在您的 中checkstyle.xml,将SuppressWarningsHolder模块添加到TreeWalker

<module name="TreeWalker">
    <!-- Make the @SuppressWarnings annotations available to Checkstyle -->
    <module name="SuppressWarningsHolder" />
</module>

Next, enable the SuppressWarningsFilterthere (as a sibling to TreeWalker):

接下来,启用SuppressWarningsFilterthere(作为 的同级TreeWalker):

<!-- Filter out Checkstyle warnings that have been suppressed with the @SuppressWarnings annotation -->
<module name="SuppressWarningsFilter" />

<module name="TreeWalker">
...

Now you can annotate e.g. the method you want to exclude from a certain Checkstyle rule:

现在您可以注释例如要从某个 Checkstyle 规则中排除的方法:

@SuppressWarnings("checkstyle:methodlength")
@Override
public boolean equals(Object obj) {
    // very long auto-generated equals() method
}

The checkstyle:prefix in the argument to @SuppressWarningsis optional, but I like it as a reminder where this warning came from. The rule name must be lowercase.

checkstyle:参数中的前缀@SuppressWarnings是可选的,但我喜欢用它来提醒这个警告的来源。规则名称必须小写。

Lastly, if you're using Eclipse, it will complain about the argument being unknown to it:

最后,如果您使用 Eclipse,它会抱怨它不知道该参数:

Unsupported @SuppressWarnings("checkstyle:methodlength")

不支持@SuppressWarnings("checkstyle:methodlength")

You can disable this Eclipse warning in the preferences if you like:

如果您愿意,可以在首选项中禁用此 Eclipse 警告:

Preferences:
  Java
  --> Compiler
  --> Errors/Warnings
  --> Annotations
  --> Unhandled token in '@SuppressWarnings': set to 'Ignore'

回答by Joao Baltazar

Every answer refering to SuppressWarningsFilteris missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

每个引用SuppressWarningsFilter 的答案都缺少一个重要的细节。如果在 checkstyle-config.xml 中定义了全小写的 id,则只能使用全小写的 id。如果不是,则必须使用原始模块名称。

For instance, if in my checkstyle-config.xml I have:

例如,如果在我的 checkstyle-config.xml 我有:

<module name="NoWhitespaceBefore"/>

I cannot use:

我不能使用:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

但是,我必须使用:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

为了使第一个语法起作用,checkstyle-config.xml 应该具有:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

这对我有用,至少在 CheckStyle 6.17 版中如此。

回答by Saltymule

I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

我对上面的答案有困难,可能是因为我将 checkStyle 警告设置为错误。什么工作是 SuppressionFilter:http: //checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.

这样做的缺点是行范围存储在单独的suppressions.xml 文件中,因此不熟悉的开发人员可能无法立即建立连接。

回答by Roberto

<module name="Checker">
    <module name="SuppressionCommentFilter"/>
    <module name="TreeWalker">
        <module name="FileContentsHolder"/>
    </module>
</module>

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

要配置过滤器以抑制包含 BEGIN GENERATED CODE 行的注释和包含 END GENERATED CODE 行的注释之间的审计事件:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
  <property name="onCommentFormat" value="END GENERATED CODE"/>
</module>

//BEGIN GENERATED CODE
@Override
public boolean equals(Object obj) { ... } // No violation events will be reported

@Override
public int hashCode() { ... } // No violation events will be reported
//END GENERATED CODE

See more

查看更多

回答by fernal73

You could try out https://checkstyle.sourceforge.io/config_filters.html#SuppressionXpathFilter

你可以试试 https://checkstyle.sourceforge.io/config_filters.html#SuppressionXpathFilter

Generate Xpath suppressions using the CLI with the -g option. Then, pick the suppression element specific to the line you wish to suppress. Save that in a suppressions file and specify that file path in the SuppressionXpathFilter element above.

使用带有 -g 选项的 CLI 生成 Xpath 抑制。然后,选择特定于您要抑制的行的抑制元素。将其保存在抑制文件中,并在上面的 SuppressionXpathFilter 元素中指定该文件路径。

https://checkstyle.sourceforge.io/cmdline.html#Command_line_usage

https://checkstyle.sourceforge.io/cmdline.html#Command_line_usage

If you're using ant, you can refer to this post as an ant task to be used to generate a suppressions Xpath file.

如果您正在使用 ant,您可以将这篇文章称为用于生成抑制 Xpath 文件的 ant 任务。

https://github.com/checkstyle/checkstyle/issues/6934#issuecomment-522289083

https://github.com/checkstyle/checkstyle/issues/6934#issuecomment-522289083

Check out this thread about how to use the filter:

查看有关如何使用过滤器的线程:

https://groups.google.com/forum/m/#!topic/checkstyle/F_f6R_Qk1EM

https://groups.google.com/forum/m/#!topic/checkstyle/F_f6R_Qk1EM