我有這個簡單的ldap客戶端,它使用過時的Hashtable
集合。替換過時的`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();
}
}
}
是否有任何現代集合,我可以使用不破壞代碼而不是哈希表?
更新:
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();
}
}
}
您必須使用遺留類的唯一時間是當您有一個需要它的API時。在這種情況下,你必須通過一個Hashtable。 –
您可以改用Properties對象。 Properties類不被視爲已過時。屬性擴展了HashTable,所以它可以傳遞給InitialDirContext構造函數。 (當然,這並不意味着你真的避免使用HashTable,但至少你的代碼不會直接使用過時的類。) – VGR