java utility class_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中排除:对我来说,它在语义上比添加私有构造函数更正确应用入口点.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值