【问题标题】:Sonar: Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap"声纳:将同步类“Hashtable”替换为非同步类,例如“HashMap”
【发布时间】:2020-06-14 19:57:12
【问题描述】:

我无法用哈希表替换哈希表,因为我使用的方法接收哈希表:

private Context getInitialContext() throws NamingException {

        final Hashtable<String, Object> jndiProperties = new Hashtable<>();

        jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        // This "new InitialContext()" receives a Hastable, and I can't modify that
        // because that is part of a jar
        // "javax.naming.InitialContext.InitialContext(Hashtable<?, ?> environment)
        // throws NamingException"
        context = new InitialContext(jndiProperties);

        return context;
    }

InitialContext 方法:

public InitialContext(Hashtable<?,?> environment)
        throws NamingException
    {
        if (environment != null) {
            environment = (Hashtable)environment.clone();
        }
        init(environment);
    }

我可以做些什么来解决这个代码问题?

【问题讨论】:

    标签: java sonarqube sonarlint


    【解决方案1】:

    看到 Sonar 在另一个投诉解决方案中使用 Hashtable 令人惊讶。

    https://rules.sonarsource.com/java/type/Vulnerability/RSPEC-4433

    【讨论】:

      【解决方案2】:

      如果您必须让 SonarQube 满意并使用 InitialContext,请考虑使用

      Properties

      见: https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html

      所以而不是:

      final Hashtable<String, Object> jndiProperties = new Hashtable<>();
      

      用途:

      final Properties jndiProperties = new Properties();
      

      JavaDocs 中的注释:

      因为 Properties 继承自 Hashtable,所以 put 和 putAll 方法 可以应用于 Properties 对象。他们的使用非常强烈 不鼓励,因为它们允许调用者插入其键或 值不是字符串。应该改用 setProperty 方法。 如果在“受损”属性上调用 store 或 save 方法 包含非字符串键或值的对象,调用将失败。 同样,对 propertyNames 或 list 方法的调用将失败,如果 它在包含一个“妥协”的 Properties 对象上调用 非字符串键。

      这意味着您的原始代码示例应如下所示:

          private Context getInitialContext() throws NamingException {
      
          final Properties jndiProperties = new Properties();
      
          jndiProperties.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
          // This "new InitialContext()" receives a Hastable, and I can't modify that
          // because that is part of a jar
          // "javax.naming.InitialContext.InitialContext(Hashtable<?, ?> environment)
          // throws NamingException"
          context = new InitialContext(jndiProperties);
      
          return context;
      }
      

      【讨论】:

        【解决方案3】:

        由于InitialContext 实际上需要Hashtable(这是一个糟糕的API 决定,但它可能在Map 在Java 中出现之前就已经解决了)所以真的没有办法完全避免Hashtable。在这种情况下,抑制声纳中的警告(或将其标记为 WontFix 或误报)是适当的反应。

        【讨论】:

        • 你如何“标记为 WontFix”?
        • @FlorianCastelain:我们正在使用 SonarCube,它可以通过 Web UI 完成,老实说,我不知道这是否是纯声纳的选项,您可能需要注释或代码注释。
        猜你喜欢
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        • 2014-01-03
        • 1970-01-01
        • 2014-09-09
        • 2010-11-20
        • 1970-01-01
        相关资源
        最近更新 更多