一般來說,開發人員偶爾會遇到這樣的情形: 在一個特定容器中映射任意類型的值。然而Java 集合API只提供了參數化的容器。這限制了類型安全地使用HashMap,如單一的值類型。但如果想混合蘋果和梨,該怎樣做呢?
考慮一個例子,你需要提供某種應用程序的上下文,它可以將特定的鍵綁定到任意類型的值。利用String作為鍵的HashMap,一個簡單的、非類型安全(type safe)的實現可能是這樣的:
public class Context {
private final Map<String,Object> values = new HashMap<>();
public void put( String key, Object value ) {
values.put( key, value );
}
public Object get( String key ) {
return values.get( key );
}
}
接下來的代碼片段展示了怎樣在程序中使用Context :
Context context = new Context();
Runnable runnable = ...
context.put( "key", runnable );
// several computation cycles later...
Runnable value = ( Runnable )context.get( "key" );
可以看出,這種方法的缺點是在第6行需要進行向下轉型(down cast)。如果替換鍵值對中值的類型,顯然會拋出一個ClassCastException異常:
Context context = new Context();
Runnable runnable = ...
context.put( "key", runnable );
// several computation cycles later...
Executor executor = ...
context.put( "key", executor );
// even more computation cycles later...
Runnable value = ( Runnable )context.get( "key" ); // runtime problem
產生這種問題的原因是很難被跟蹤到的,因為相關的實現步驟可能已經廣泛分布在你的程序各個部分中。
為了改善這種情況,貌似將value和它的key、它的value都進行綁定是合理的。
public class Context {
private final <String, Object> values = new HashMap<>();
public <T> void put( String key, T value, Class<T> valueType ) {
values.put( key, value );
}
public <T> T get( String key, Class<T> valueType ) {
return ( T )values.get( key );
}
}
同樣的基本用法可能是這樣的:
Context context = new Context();
Runnable runnable = ...
context.put( "key", runnable, Runnable.class );
// several computation cycles later...
Runnable value = context.get( "key", Runnable.class );
乍一看,這段代碼可能會給你更類型安全的錯覺,因為其在第6行避免了向下轉型(down cast)。但是運行下面的代碼將使我們重返現實,因為我們仍將在最后一行賦值語句處跌入ClassCastException 的懷抱:
Context context = new Context();
Runnable runnable = ...
context.put( "key", runnable, Runnable.class );
// several computation cycles later...
Executor executor = ...
context.put( "key", executor, Executor.class );
// even more computation cycles later...
Runnable value = context.get( "key", Runnable.class );
哪里出問題了呢?
首先,Context.get中的向下轉型是無效的,因為類型擦除會使用靜態轉型的Object來代替無界參數(unbonded parameters)。此外更重要的是,這個實現根本就沒有用到由Context.put提供的類型信息。這充其量是多此一舉的美容罷了。
靜態轉型
Object obj; // may be an integer
if (obj instanceof Integer) {
Integer objAsInt = (Integer) obj;
// do something with 'objAsInt'
}
這里使用了 instanceof 和轉型操作符,這些操作符已經融入到語言當中了。對象轉換的類型(這個例子中是Integer)必須是在編譯期靜態確定的,所以我們將這種轉型稱為靜態轉型。
類型安全的異構容器
雖然上面Context 的變種不起作用,但卻指明了方向。接下來的問題是:怎樣合理地參數化這個key? 為了回答這個問題,讓我們先看看一個根據Bloch所描述的類型安全異構容器模式(typesafe heterogenous container pattern)的簡裝實現吧。
我們的想法是用key自身的class 類型作為key。因為Class 是參數化的類型,它可以確保我們使Context方法是類型安全的,而無需訴諸于一個未經檢查的強制轉換為T。這種形式的一個Class 對象稱之為類型令牌(type token)。
public class Context {
private final Map<Class<?>, Object> values = new HashMap<>();
public <T> void put( Class<T> key, T value ) {
values.put( key, value );
}
public <T> T get( Class<T> key ) {
return key.cast( values.get( key ) );
}
}
請注意在Context#get 的實現中是如何用一個有效的動態變量替換向下轉型的。客戶端可以這樣使用這個context:
Context context = new Context();
Runnable runnable ...
context.put( Runnable.class, runnable );
// several computation cycles later...
Executor executor = ...
context.put( Executor.class, executor );
// even more computation cycles later...
Runnable value = context.get( Runnable.class );
這次客戶端的代碼將可以正常工作,不再有類轉換的問題,因為不可能通過一個不同的值類型來交換某個鍵值對。
Bloch指出這種模式有兩個局限性。“首先,惡意的客戶端可以通過以原生態形式(raw form)使用class對象輕松地破壞類型安全。”為了確保在運行時類型安全可以在Context#put中使用動態轉換(dynamic cast)。
public <T> void put( Class<T> key, T value ) {
values.put( key, key.cast( value ) );
}
第二個局限在于它不能用在不可具體化(non-reifiable )的類型中(見《Effective Java》第25項)。換句話說,你可以保存Runnable 或Runnable[],但是不能保存List<Runnable>。
這是因為List<Runnable>沒有特定class對象,所有的參數化類型指的是相同的List.class 對象。因此,Bloch指出對于這種局限性沒有滿意的解決方案。
但是,假如你需要存儲兩個具有相同值類型的條目該怎么辦呢?如果僅為了存入類型安全的容器,可以考慮創建新的類型擴展,但這顯然不是最好的設計。使用定制的Key也許是更好的方案。
多條同類型容器條目
為了能夠存儲多條同類型容器條目,我們可以用自定義key改變Context 類。這種key必須提供我們類型安全所需的類型信息,以及區分不同的值對象(value objects)的標識。一個以String 實例為標識的、幼稚的key實現可能是這樣的:
public class Key<T> {
final String identifier;
final Class<T> type;
public Key( String identifier, Class<T> type ) {
this.identifier = identifier;
this.type = type;
}
}
我們再次使用參數化的Class作為類型信息的鉤子,調整后的Context將使用參數化的Key而不是Class。
public class Context {
private final Map<Key<?>, Object> values = new HashMap<>();
public <T> void put( Key<T> key, T value ) {
values.put( key, value );
}
public <T> T get( Key<T> key ) {
return key.type.cast( values.get( key ) );
}
}
客戶端將這樣使用這個版本的Context:
Context context = new Context();
Runnable runnable1 = ...
Key<Runnable> key1 = new Key<>( "id1", Runnable.class );
context.put( key1, runnable1 );
Runnable runnable2 = ...
Key<Runnable> key2 = new Key<>( "id2", Runnable.class );
context.put( key2, runnable2 );
// several computation cycles later...
Runnable actual = context.get( key1 );
assertThat( actual ).isSameAs( runnable1 );
雖然這個代碼片段可用,但仍有缺陷。在Context#get中,Key被用作查詢參數。用相同的identifier和class初始化兩個不同的Key的實例,一個用于put,另一個用于get,最后get操作將返回null 。這不是我們想要的……
//譯者附代碼片段
Context context = new Context();
Runnable runnable1 = ...
Key<Runnable> key1 = new Key<>( "same-id", Runnable.class );
Key<Runnable> key2 = new Key<>( "same-id", Runnable.class );
context.put( key1, runnable1 );//一個用于put
context.get(key2); //另一個用于get --> return null;
幸運的是,為Key設計合適的equals 和hashCode 可以輕松解決這個問題,進而使HashMap 查找按預期工作。最后,你可以為創建key提供一個工廠方法以簡化其創建過程(與static import一起使用時有用):
public static Key key( String identifier, Class type ) {
return new Key( identifier, type );
}
結論
“集合API說明了泛型的一般用法,限制你每個容器只能有固定數目的類型參數。你可以通過將類型參數放在鍵上而不是容器上來避開這個限制。對于這種類型安全的 異構容器,可以用Class對應作為鍵。”(Joshua Bloch,《Effective Java》第29項)。
給出上述閉幕詞,也沒有什么要補充的了,除了祝愿你成功混合蘋果和梨……
轉自:http://www.importnew.com/15556.html