zoukankan      html  css  js  c++  java
  • 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构造函数

  • 相关阅读:
    雪妖现世:给SAP Fiori Launchpad增添雪花纷飞的效果
    ABAP开发环境语法高亮的那些事儿
    如何使用Prometheus采集SAP ABAP Netweaver的应用日志数据
    如何免费试用SAP的Fiori应用
    使用ABAP绘制可伸缩矢量图
    背景建模
    C# 属性和索引
    Equation
    Phone numbers
    BerOS file system
  • 原文地址:https://www.cnblogs.com/UniqueColor/p/9298541.html
Copyright © 2011-2022 走看看