java – 为什么主Spring Boot应用程序总是触发PMD的HideUtilityClassConstructorCheck?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 为什么主Spring Boot应用程序总是触发PMD的HideUtilityClassConstructorCheck?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1922字,纯文字阅读大概需要3分钟。
内容图文
标准的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中排除:对我来说,它在语义上比添加私有构造函数更正确应用入口点.
内容总结
以上是互联网集市为您收集整理的java – 为什么主Spring Boot应用程序总是触发PMD的HideUtilityClassConstructorCheck?全部内容,希望文章能够帮你解决java – 为什么主Spring Boot应用程序总是触发PMD的HideUtilityClassConstructorCheck?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。