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

标签 java

我有一个简单的 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/

相关文章:

java - 为什么 fn :matches and fn:replace throwing parse errors in XSLT 2. 是 0?

java - 使用 paintComponent() 在 JFrame 中绘制矩形

java - 如何在JAVA中映射出SQL UDT数组的参数?

java - SQLite数据库创建失败,文档不清楚

java - 样式 toast 背景 - 找不到与给定名称匹配的资源

java - 查找是否存在于枚举中而不进行迭代?

java - Bamboo 安装软件

java - 将 SecureRandom 与 SHA-256 结合使用

java - 谷歌地图只显示灰色背景而不是 map

java - 如何从 servlet 获取下拉列表的 Selected INDEX?