如何使用 main 方法抑制类的 checkstyle HideUtilityClassConstructor 规则?

问题描述

我想取消具有 main 方法的类的“HideUtilityClassConstructor”规则。 看起来像这样:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
   public static void main(String[] args) {
       SpringApplication.run(Application.class,args);
   }
}
@H_404_6@
  • 由于所有 checkstyle 规则都位于公共库中 - 它应该是使用这些规则的任何模块的通用跳过。
  • 主类的名称可以不同(跳过应该应用于所有具有公共静态 main 方法的类)
  • 更改应位于 checkstyle 通用 xml 文件中(不在主类中,例如使用 @SupressWarnings 或注释)
  • 可以吗?

    解决方法

    您可以通过 SuppressionXpathFilter 实现这一点。 例如,对于您的代码,您需要将此模块添加到您的配置中(在此示例中,抑制位于文件抑制.xml 中)

    <?xml version="1.0"?>
    <!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">
    <module name = "Checker">
    
        <module name="TreeWalker">
            <module name="SuppressionXpathFilter">
                <property name="file" value="suppressions.xml"/>
                <property name="optional" value="false"/>
            </module>
            <module name="HideUtilityClassConstructor"/>
        </module>
    </module>
    

    而suppressions.xml 文件的内容是这样的。这里有 2 个抑制,您可以选择其中任何一个。 Second 对我来说看起来更好,因为可能的误报更少。

    <?xml version="1.0"?>
    
    <!DOCTYPE suppressions PUBLIC
    "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
    "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">
    
    <suppressions>
      <!--  Suppress for any classes that contain method named "main"  -->
      <suppress-xpath checks="HideUtilityClassConstructor"
      query="//CLASS_DEF[//METHOD_DEF[./IDENT[@text='main']]]"/>
    
      <!--  Suppress for any classes that are annotated with "SpringBootApplication"  -->
      <suppress-xpath checks="HideUtilityClassConstructor"
       query="//CLASS_DEF[//MODIFIERS/ANNOTATION[./IDENT[@text='SpringBootApplication']]]"/>
    
    </suppressions>