【问题标题】:Checkstyle errors while using Lombok使用 Lombok 时出现 Checkstyle 错误
【发布时间】:2015-04-14 12:18:39
【问题描述】:

在编译以下使用 Lombok 自动生成 getter 和 setter 的类时,Checkstyle 会引发编译错误:

实用程序类不应有公共或默认构造函数

@Getter
@Setter
public class foo {
    private String type;
    private int value;
}

当Checkstyle不遵循checkstyle's documentation中指定的实用程序类定义时,为什么将上述类归类为实用程序类?即仅包含静态方法或字段的类。 checkstyle是解析默认的源文本文件还是lombok生成的源文件?

【问题讨论】:

标签: java checkstyle lombok


【解决方案1】:

Checkstyle 适用于源代码,它看不到 lombok 会生成字节码,因此它看到一个只有两个私有字段的类,它假定您有一个实用程序类。 一个实用程序类应该有一个 private 构造函数,以防这种检查样式,但您可能不希望这样(您将无法创建此类的实例),因此您需要要么删除 HideUtilityClassConstructor checkstyle 规则列表,或添加(见http://checkstyle.sourceforge.net/config_annotation.html#SuppressWarnings#SuppressWarningsHolder@SuppressWarnings("checkstyle:HideUtilityClassConstructor")

@Getter
@Setter
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
public class foo {
    private String type;
    private int value;
}

【讨论】:

    【解决方案2】:

    使用 checkstyle 有一个不错的 XPathSuppressionFilter。使用它

    添加到您的 checkstyle.xml 文件中

      <!-- externalize the ignored/suppressed checks -->
      <module name="SuppressionFilter">
         <property name="file" value="./checkstyle-suppressions.xml" />
         <property name="optional" value="false" />
      </module>
    

    在 checkstyle-suppressions.xml 中

    <!-- disable checks against lombok annotations -->
    <suppress-xpath checks="HideUtilityClassConstructor" query="//CLASS_DEF[.//ANNOTATION/IDENT[@text='UtilityClass']]"/>
    <suppress-xpath checks="HideUtilityClassConstructor" query="//CLASS_DEF[.//ANNOTATION/IDENT[@text='Getter']]"/>
    <suppress-xpath checks="HideUtilityClassConstructor" query="//CLASS_DEF[.//ANNOTATION/IDENT[@text='Setter']]"/>
    

    【讨论】:

      【解决方案3】:

      如果注释对您不起作用,(由于您使用的 checkstyle 版本),您可以使用

      // CHECKSTYLE:SUPPRESS:HideUtilityClassConstructor
      @Getter
      @Setter
      public class Foo {
          private String type;
          private int value;
      }
      // CHECKSTYLE:UNSUPPRESS:HideUtilityClassConstructor
      

      改为。

      【讨论】:

        猜你喜欢
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 2022-11-08
        相关资源
        最近更新 更多