java – 为什么主Spring Boot应用程序总是触发PMD的HideUtilityClassConstructorCheck?

标准的
Spring Boot应用程序有一些主要的方法类文件,比如SampleApplication.java,如下所示:

@SpringBootApplication
@RestController
public class SampleApplication {

    public static void main(final String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}

但PMD静态分析将其标记为错误(HideUtilityClassConstructorCheck):

Utility classes
should not have a public or default constructor.

Makes sure that utility classes (classes that contain only static
methods or fields in their API) do not have a public constructor.

Rationale: Instantiating utility classes does not make sense. Hence
the constructors should either be private or (if you want to allow
subclassing) protected. A common mistake is forgetting to hide the
default constructor.

If you make the constructor protected you may want to consider the
following constructor implementation technique to disallow
instantiating subclasses:

public class StringUtils // not final to allow subclassing { protected
StringUtils() { // prevents calls from subclass throw new
UnsupportedOperationException(); } public static int count(char c,
String s) { // … } }

为什么是这样?我应该抑制这个PMD错误吗?

最佳答案 检查说明了一切.

默认情况下,任何代码检查器(IntelliJ IDEA,FindBugs,PMD,Sonar)都假设如果类只有静态方法,那么它是utility class.实用程序类的示例是java.lang.Math,如下所示:

public final class Math {

    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {}

    public static double exp(double a) {
        ...
    }

    // More helper methods
}

这样的类被设计为将它用作一组静态函数:为它声明私有构造函数是一个好习惯,因此没有人会错误地实例化它并声明类final,因为扩展它是没有意义的.

在您的情况下(以及几乎每个Spring Boot应用程序的入口点)SampleApplication类都有一个公共静态void main方法,因此PMD决定其实用程序类,检查私有构造和最终修饰符并标记错误.这不是问题,PMD只是不了解Spring Boot或任何其他框架及其入口点,因此完全有理由抑制此警告并将您的类从PMD中排除:对我来说,它在语义上比添加私有构造函数更正确应用入口点.

点赞