在编译以下使用 Lombok 自动生成 getter 和 setter 的类时,Checkstyle 会抛出编译错误:
实用程序类不应具有公共或默认构造函数
@Getter
@Setter
public class foo {
private String type;
private int value;
}
为什么 Checkstyle 将上述类归类为实用程序类,而它不遵循 checkstyle 文档中指定的实用程序类定义?即仅包含静态方法或字段的类。 checkstyle解析的是默认的源文本文件还是lombok生成的源文件?
Checkstyle 适用于源代码,它看不到 lombok 会生成字节码,因此它看到一个只有两个私有字段的类,它假设您有一个实用程序类。 实用程序类应该有一个
private
构造函数,以防出现该 checkstyle,但您可能不希望这样(您将无法创建此类的实例),所以您需要的是从中删除 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;
}
使用 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']]"/>
如果注释对您不起作用(由于您正在使用的 checkstyle 版本),您可以使用
// CHECKSTYLE:SUPPRESS:HideUtilityClassConstructor
@Getter
@Setter
public class Foo {
private String type;
private int value;
}
// CHECKSTYLE:UNSUPPRESS:HideUtilityClassConstructor
相反。
使用较新版本的 Checkstyle,您在使用 Lombok 中的
@Getter
和 @Setter
时不应再遇到实用程序类错误。
但是,如果您也想忽略 Lombok 中用
@UtilityClass
注释的类,从 Checkstyle 版本 10.20.0
开始,您可以使用 ignoreAnnotatedBy
标签更轻松地忽略它(不需要抑制过滤器):
<module name="HideUtilityClassConstructor">
<property name="ignoreAnnotatedBy"
value="UtilityClass"/>
</module>
如果你想忽略更多注释,你可以这样做:
<module name="HideUtilityClassConstructor">
<property name="ignoreAnnotatedBy"
value="SpringBootApplication, UtilityClass, java.lang.Deprecated, Deprecated"/>
</module>