我无法为 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/