add a private constructor to hide the implicit public one(Utility classes should not have public constructors)


sonarlint提示add a private constructor to hide the implicit public one

Utility classes should not have public constructors

Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant

  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }

}
Compliant Solution
class StringUtils { // Compliant

  private StringUtils() {
    throw new IllegalStateException("Utility class");
  }

  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }

}
Exceptions
When class contains public static void main(String[] args) method it is not considered as utility class and will be ignored by this rule.

 

意思是util類里面都是靜態方法,不會去初始化這個類,所以不應該暴露一個public構造函數

解決方案:

     定義一個private構造函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM