gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:22:06 28 4
gpt4 key购买 nike

我无法为 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 methodscan be applied to a Properties object. Their use is stronglydiscouraged as they allow the caller to insert entries whose keys orvalues are not Strings. The setProperty method should be used instead.If the store or save method is called on a "compromised" Propertiesobject that contains a non-String key or value, the call will fail.Similarly, the call to the propertyNames or list method will fail ifit is called on a "compromised" Properties object that contains anon-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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com