如何使用Java泛型映射不同的值類型

字號(hào):


    一般來說,開發(fā)人員偶爾會(huì)遇到這樣的情形: 在一個(gè)特定容器中映射任意類型的值。然而Java 集合API只提供了參數(shù)化的容器。這限制了類型安全地使用HashMap,如單一的值類型。但如果想混合蘋果和梨,該怎樣做呢?
    幸運(yùn)的是,有一個(gè)簡單的設(shè)計(jì)模式允許使用Java泛型映射不同的值類型,Joshua Bloch在其《Effective Java》(第二版,第29項(xiàng))中將其描述為類型安全的異構(gòu)容器(typesafe hetereogeneous container)。
    關(guān)于這個(gè)主題,最近碰到一些不太合適的解決方案。它給了我在這篇文章中解釋這個(gè)問題域,并闡述一些實(shí)現(xiàn)細(xì)節(jié)的想法。
    使用Java泛型映射不同的值類型
    考慮一個(gè)例子,你需要提供某種應(yīng)用程序的上下文,它可以將特定的鍵綁定到任意類型的值。利用String作為鍵的HashMap,一個(gè)簡單的、非類型安全(type safe)的實(shí)現(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" );
    可以看出,這種方法的缺點(diǎn)是在第6行需要進(jìn)行向下轉(zhuǎn)型(down cast)。如果替換鍵值對(duì)中值的類型,顯然會(huì)拋出一個(gè)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)生這種問題的原因是很難被跟蹤到的,因?yàn)橄嚓P(guān)的實(shí)現(xiàn)步驟可能已經(jīng)廣泛分布在你的程序各個(gè)部分中。
    為了改善這種情況,貌似將value和它的key、它的value都進(jìn)行綁定是合理的。
    在我看到的、按照這種方法的多種解決方案中,常見的錯(cuò)誤或多或少歸結(jié)于下面Context的變種:
    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 );
    乍一看,這段代碼可能會(huì)給你更類型安全的錯(cuò)覺,因?yàn)槠湓诘?行避免了向下轉(zhuǎn)型(down cast)。但是運(yùn)行下面的代碼將使我們重返現(xiàn)實(shí),因?yàn)槲覀內(nèi)詫⒃诘?0行賦值語句處跌入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 ); // runtime problem
    哪里出問題了呢?
    首先,Context#get中的向下轉(zhuǎn)型是無效的,因?yàn)轭愋筒脸龝?huì)使用靜態(tài)轉(zhuǎn)型的Object來代替無界參數(shù)(unbonded parameters)。此外更重要的是,這個(gè)實(shí)現(xiàn)根本就沒有用到由Context#put 提供的類型信息。這充其量是多此一舉的美容罷了。
    類型安全的異構(gòu)容器
    雖然上面Context 的變種不起作用,但卻指明了方向。接下來的問題是:怎樣合理地參數(shù)化這個(gè)key? 為了回答這個(gè)問題,讓我們先看看一個(gè)根據(jù)Bloch所描述的類型安全異構(gòu)容器模式(typesafe heterogenous container pattern)的簡裝實(shí)現(xiàn)吧。
    我們的想法是用key自身的class 類型作為key。因?yàn)镃lass 是參數(shù)化的類型,它可以確保我們使Context方法是類型安全的,而無需訴諸于一個(gè)未經(jīng)檢查的強(qiáng)制轉(zhuǎn)換為T。這種形式的一個(gè)Class 對(duì)象稱之為類型令牌(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 ) );
    }
    [...]
    }
    請(qǐng)注意在Context#get 的實(shí)現(xiàn)中是如何用一個(gè)有效的動(dòng)態(tài)變量替換向下轉(zhuǎn)型的??蛻舳丝梢赃@樣使用這個(gè)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)換的問題,因?yàn)椴豢赡芡ㄟ^一個(gè)不同的值類型來交換某個(gè)鍵值對(duì)。
    有光明的地方就必然有陰影,有陰影的地方就必然有光明。不存在沒有陰影的光明,也不存在沒有光明的陰影。村上春樹
    Bloch指出這種模式有兩個(gè)局限性?!笆紫?,惡意的客戶端可以通過以原生態(tài)形式(raw form)使用class對(duì)象輕松地破壞類型安全?!睘榱舜_保在運(yùn)行時(shí)類型安全可以在Context#put中使用動(dòng)態(tài)轉(zhuǎn)換(dynamic cast)。
    public <T> void put( Class<T> key, T value ) {
    values.put( key, key.cast( value ) );
    }
    第二個(gè)局限在于它不能用在不可具體化(non-reifiable )的類型中(見《Effective Java》第25項(xiàng))。換句話說,你可以保存Runnable 或Runnable[],但是不能保存List<Runnable>。
    這是因?yàn)長ist<Runnable>沒有特定class對(duì)象,所有的參數(shù)化類型指的是相同的List.class 對(duì)象。因此,Bloch指出對(duì)于這種局限性沒有滿意的解決方案。
    但是,假如你需要存儲(chǔ)兩個(gè)具有相同值類型的條目該怎么辦呢?如果僅為了存入類型安全的容器,可以考慮創(chuàng)建新的類型擴(kuò)展,但這顯然不是最好的設(shè)計(jì)。使用定制的Key也許是更好的方案。
    多條同類型容器條目
    為了能夠存儲(chǔ)多條同類型容器條目,我們可以用自定義key改變Context 類。這種key必須提供我們類型安全所需的類型信息,以及區(qū)分不同的值對(duì)象(value objects)的標(biāo)識(shí)。一個(gè)以String 實(shí)例為標(biāo)識(shí)的、幼稚的key實(shí)現(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;
    }
    }
    我們?cè)俅问褂脜?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 ) );
    }
    [...]
    }
    客戶端將這樣使用這個(gè)版本的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 );
    雖然這個(gè)代碼片段可用,但仍有缺陷。在Context#get中,Key被用作查詢參數(shù)。用相同的identifier和class初始化兩個(gè)不同的Key的實(shí)例,一個(gè)用于put,另一個(gè)用于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 );//一個(gè)用于put
    context.get(key2); //另一個(gè)用于get --> return null;
    幸運(yùn)的是,為Key設(shè)計(jì)合適的equals 和hashCode 可以輕松解決這個(gè)問題,進(jìn)而使HashMap 查找按預(yù)期工作。最后,你可以為創(chuàng)建key提供一個(gè)工廠方法以簡化其創(chuàng)建過程(與static import一起使用時(shí)有用):
    public static Key key( String identifier, Class type ) {
    return new Key( identifier, type );
    }
    結(jié)論
    “集合API說明了泛型的一般用法,限制你每個(gè)容器只能有固定數(shù)目的類型參數(shù)。你可以通過將類型參數(shù)放在鍵上而不是容器上來避開這個(gè)限制。對(duì)于這種類型安全的 異構(gòu)容器,可以用Class對(duì)應(yīng)作為鍵?!保↗oshua Bloch,《Effective Java》第29項(xiàng))。
    給出上述閉幕詞,也沒有什么要補(bǔ)充的了,除了祝愿你成功混合蘋果和梨……