一般來說妥曲,開發(fā)人員偶爾會遇到這樣的情形: 在一個特定容器中映射任意類型的值贾费。然而Java 集合API只提供了參數(shù)化的容器。這限制了類型安全地使用HashMap檐盟,如單一的值類型褂萧。但如果想混合蘋果和梨,該怎樣做呢葵萎?
考慮一個例子导犹,你需要提供某種應(yīng)用程序的上下文唱凯,它可以將特定的鍵綁定到任意類型的值。利用String作為鍵的HashMap谎痢,一個簡單的磕昼、非類型安全(type safe)的實現(xiàn)可能是這樣的:
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行需要進行向下轉(zhuǎn)型(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
產(chǎn)生這種問題的原因是很難被跟蹤到的,因為相關(guān)的實現(xiàn)步驟可能已經(jīng)廣泛分布在你的程序各個部分中滨嘱。
為了改善這種情況峰鄙,貌似將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行避免了向下轉(zhuǎn)型(down cast)躺彬。但是運行下面的代碼將使我們重返現(xiàn)實煤墙,因為我們?nèi)詫⒃谧詈笠恍匈x值語句處跌入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中的向下轉(zhuǎn)型是無效的仿野,因為類型擦除會使用靜態(tài)轉(zhuǎn)型的Object來代替無界參數(shù)(unbonded parameters)。此外更重要的是她君,這個實現(xiàn)根本就沒有用到由Context.put提供的類型信息脚作。這充其量是多此一舉的美容罷了。
靜態(tài)轉(zhuǎn)型
Object obj; // may be an integer
if (obj instanceof Integer) {
Integer objAsInt = (Integer) obj;
// do something with 'objAsInt'
}
這里使用了 instanceof 和轉(zhuǎn)型操作符缔刹,這些操作符已經(jīng)融入到語言當(dāng)中了球涛。對象轉(zhuǎn)換的類型(這個例子中是Integer)必須是在編譯期靜態(tài)確定的,所以我們將這種轉(zhuǎn)型稱為靜態(tài)轉(zhuǎn)型校镐。
類型安全的異構(gòu)容器
雖然上面Context 的變種不起作用亿扁,但卻指明了方向。接下來的問題是:怎樣合理地參數(shù)化這個key鸟廓? 為了回答這個問題从祝,讓我們先看看一個根據(jù)Bloch所描述的類型安全異構(gòu)容器模式(typesafe heterogenous container pattern)的簡裝實現(xiàn)吧。
我們的想法是用key自身的class 類型作為key引谜。因為Class 是參數(shù)化的類型牍陌,它可以確保我們使Context方法是類型安全的,而無需訴諸于一個未經(jīng)檢查的強制轉(zhuǎn)換為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 的實現(xiàn)中是如何用一個有效的動態(tài)變量替換向下轉(zhuǎn)型的”词遥客戶端可以這樣使用這個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 );
這次客戶端的代碼將可以正常工作契讲,不再有類轉(zhuǎn)換的問題仿吞,因為不可能通過一個不同的值類型來交換某個鍵值對。
Bloch指出這種模式有兩個局限性怀泊∶2兀“首先,惡意的客戶端可以通過以原生態(tài)形式(raw form)使用class對象輕松地破壞類型安全霹琼∥癜粒”為了確保在運行時類型安全可以在Context#put中使用動態(tài)轉(zhuǎn)換(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對象挟伙,所有的參數(shù)化類型指的是相同的List.class 對象。因此模孩,Bloch指出對于這種局限性沒有滿意的解決方案尖阔。
但是,假如你需要存儲兩個具有相同值類型的條目該怎么辦呢榨咐?如果僅為了存入類型安全的容器介却,可以考慮創(chuàng)建新的類型擴展,但這顯然不是最好的設(shè)計块茁。使用定制的Key也許是更好的方案齿坷。
多條同類型容器條目
為了能夠存儲多條同類型容器條目,我們可以用自定義key改變Context 類数焊。這種key必須提供我們類型安全所需的類型信息永淌,以及區(qū)分不同的值對象(value objects)的標識。一個以String 實例為標識的佩耳、幼稚的key實現(xiàn)可能是這樣的:
public class Key<T> {
final String identifier;
final Class<T> type;
public Key( String identifier, Class<T> type ) {
this.identifier = identifier;
this.type = type;
}
}
我們再次使用參數(shù)化的Class作為類型信息的鉤子遂蛀,調(diào)整后的Context將使用參數(shù)化的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被用作查詢參數(shù)萍诱。用相同的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設(shè)計合適的equals 和hashCode 可以輕松解決這個問題籍凝,進而使HashMap 查找按預(yù)期工作周瞎。最后,你可以為創(chuàng)建key提供一個工廠方法以簡化其創(chuàng)建過程(與static import一起使用時有用):
public static Key key( String identifier, Class type ) {
return new Key( identifier, type );
}
結(jié)論
“集合API說明了泛型的一般用法饵蒂,限制你每個容器只能有固定數(shù)目的類型參數(shù)声诸。你可以通過將類型參數(shù)放在鍵上而不是容器上來避開這個限制。對于這種類型安全的 異構(gòu)容器退盯,可以用Class對應(yīng)作為鍵彼乌。”(Joshua Bloch渊迁,《Effective Java》第29項)慰照。
給出上述閉幕詞,也沒有什么要補充的了琉朽,除了祝愿你成功混合蘋果和梨……
轉(zhuǎn)自:http://www.importnew.com/15556.html