java - Sonar : Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap"

标签 java sonarqube sonarlint

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

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;
    }

初始上下文方法:
public InitialContext(Hashtable<?,?> environment)
        throws NamingException
    {
        if (environment != null) {
            environment = (Hashtable)environment.clone();
        }
        init(environment);
    }

我能做些什么来解决这个代码气味?

最佳答案

如果您必须让 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 的注释:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.


这意味着您的原始代码示例应如下所示:
    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;
}

关于java - Sonar : Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60490240/

相关文章:

java - 如何比较jLabel的边框粗细?

java - Java内部类需要final变量的复杂性?

java - 如何使用antlr生成Java CFG(控制流图)?

c# - Teamcity、Sonar 和 C#/.NET

android - SonarLint 命令行工具 - 添加文件/文件夹异常(exception)

SonarQube 和 SonarLint 区别

java - if-else 结构中的不可访问代码

c# - 无法将下载的代码覆盖工具转换为 XML

java - Jacoco eclipse插件和SonarQube中的代码覆盖百分比值不同

sonarqube - 如何在 Eclipse 中将证书添加到 SonarLint