gpt4 book ai didi

java - 替换过时的 `Hashtable` 集合

转载 作者:行者123 更新时间:2023-11-29 05:31:19 26 4
gpt4 key购买 nike

我有这个简单的 ldap 客户端,它使用过时的 Hashtable 集合。

class SAuth {

public static void main(String[] args) {

Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");

try {

DirContext ctx = new InitialDirContext(env);
System.out.println(" i guess the connection is sucessfull :)");

// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}

}
}

有没有我可以在不破坏代码的情况下使用任何现代集合来代替 Hashtable?

更新:

class tSAuth {

public static void main(String[] args) {

Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");

try {

DirContext ctx = new InitialDirContext((Hashtable<?, ?>) env);
System.out.println(" i guess the connection is sucessfull :)");

// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}

}
}

最佳答案

使用 HashMap而不是 HashTable像这样:

Map env = new HashMap();

我不确定 Context.* 的确切类型,但是,如果它是 String ,那么你可以这样写代码:

Map<String, String> env = new HashMap<String, String>();

编辑:

InitialDirContext 构造函数的参数类型是Hashtable<?,?> .所以你应该 Hashtable在这种情况下。也许你可以这样编码:

Hashtable<String, String> env = new Hashtable<String, String>();

关于java - 替换过时的 `Hashtable` 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008492/

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