2014-01-08 57 views
1

我有這個簡單的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(); 
     } 

    } 
} 
+4

您必須使用遺留類的唯一時間是當您有一個需要它的API時。在這種情況下,你必須通過一個Hashtable。 –

+1

您可以改用Properties對象。 Properties類不被視爲已過時。屬性擴展了HashTable,所以它可以傳遞給InitialDirContext構造函數。 (當然,這並不意味着你真的避免使用HashTable,但至少你的代碼不會直接使用過時的類。) – VGR

回答

3

使用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>(); 
+3

注意副作用:'Hashtable'默認是同步的,而'HashMap'不是。如果代碼使用線程,使用'Collections.synchronizedMap'添加同步可能是明智的。 – Darkhogg

+0

或者像''ConcurrentHashMap'](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html) – zapl

+0

我併發更新代碼,但我使用對象投。如何在不施放代碼的情況下實現代碼清潔? –