[英]Java - SonarQube, issue on 'Utility classes should not have public constructors' (squid:S1118) in singleton
I am performing static code analysis on old code using a SonarLint analysis.我正在使用 SonarLint 分析对旧代码执行静态代码分析。 I cannot paste the code here but it is similar to:
我无法在此处粘贴代码,但它类似于:
@SuppressWarnings("static-access")
public class SuperClass {
private SuperClass() {
}
public static SuperClass getInstance() {
return InstanceHolder.instance;
}
private static class InstanceHolder {
public final static SuperClass instance = new SuperClass();
}
public void doSomething() {
//do something
}
}
SonarQube (sonar-java: 4.2.1.6971), reports an issue on S1118 . SonarQube (sonar-java: 4.2.1.6971),报告S1118上的问题。
Adding a private constructor to InstanceHolder
has no solving effect here, since SuperClass
is the only class that can create an instance of it due to its private modifier.向
InstanceHolder
添加私有构造函数在这里没有解决效果,因为SuperClass
是唯一可以创建它的实例的类,因为它有私有修饰符。
SuperClass
can still create an instance, even with ÌnstanceHolder
having a private constructor. SuperClass
仍然可以创建一个实例,即使ÌnstanceHolder
具有私有构造函数。
BTW: adding the constructor removes the sonar-issue, so I think the analyzer marked this as a rule violation because of the internal 'UtilityClass' without further investigation.顺便说一句:添加构造函数消除了声纳问题,所以我认为分析器将此标记为违反规则,因为内部“UtilityClass”没有进一步调查。
Is this a bug?这是一个错误吗? Instead of a design flaw, this is an example of a thread-safe singleton.
这不是设计缺陷,而是线程安全单例的示例。
Make your class final so that Instance creation can be avoided.将您的类设为 final,以避免创建实例。
@SuppressWarnings("static-access")
public final class SuperClass {
private SuperClass() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.