Sonarlint檢測出如下問題:
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.
公用的工具類不應該有公共的構造函數
公用的工具類是靜態成員的集合,並不意味着要實例化。甚至擴展的抽象工具程序類也不應該有公共構造函數。
Java會向不定義構造函數的每個類添加隱式的公共構造函數。因此,應該定義至少一個非公共構造函數。
錯誤代碼示例:
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
正確代碼示例:
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
例外情況:
當類包含 public static void main(String[] args) 方法時,它不被視為工具類類,並且將被該規則忽略。