使用注释@SuppressWarnings忽略Checkstyle警告

我尝试通过带有注释@SuppressWarnings的checkstyle忽略或禁用eclipse中的一些无用警告,例如如何为特定代码行禁用特定的checkstyle规则?

但这对我不起作用。

这是checkstyle.xml

         ... 

这里是java代码:

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

同时将警告值设置为“all” @SuppressWarnings("all")@SuppressWarnings("CyclomaticComplexity")@SuppressWarnings("cyclomaticcomplexity")没有任何结果。

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

A.抑制警告filter

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

  • 必须在Checkstyle设置中启用 SuppressWarningsfilter。
  • 在SuppressWarnings注释的标记中,您必须使用全部小写的checkstyle模块的名称。
  • 可选地,可以在标签中使用前缀 “checkstyle:”。
  • 如果注释无法按预期工作,请尝试更改其位置 。 MagicNumber模块的注释需要放在方法之前。 某些注释必须直接位于显示问题的位置,而其他注释必须位于类定义的前面。

checkstyle模块“MagicNumber”的一些示例:

作品:

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

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

不起作用:

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

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

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

进一步说明

  • 我收到了一个警告不支持的抑制警告,我在Eclipse首选项中禁用了Java => Compiler => Errors / Warnings => Annotations =>’@SuppressWarnings’中的未处理令牌:忽略

  • 当鼠标hover在代码问题上时,弹出的违规消息不会显示相应checkstyle模块的名称(在xml文件中定义)。 我启用了“ 包含模块ID (如果可用)违反消息”选项,并手动更改了所有模块ID,使其与xml文件中的相应模块名称相同,但小写。 例如,有一个模块,它在Eclipse checkstyle设置中显示为“Anonymous inner classes length”。 该模块没有模块ID。 我将模块ID更改为checkstyle:anoninnerlength ,以便我的同事更容易抑制警告:

    <模块>

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

B.抑制评论filter

  • checkstylefilterFilters => Suppression Comment Filter使用在xml文件中指定的模块名称。
  • 如果使用前缀“checkstyle:”,则模块名称也可以小写使用。

作品:

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

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

不起作用:

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

C.示例checkstyle settings.xml文件:

                                                                                                                                                                                                                                                                                                                                                                            

我的checkstyle版本是8.1

它适用于gradle配置,如下所示:

build.gradle

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

并忽略这样的幻数:

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

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