2012-05-29 39 views
0

我正在創建對象緩存。我無法編寫一個通用的方法返回類型(請參閱getCachedCMSObject),這樣我就不必按照註釋中所示的方法來執行返回操作。我想我可以忍受它,但我寧願使用泛型。返回通用對象

cachedCMSObject是一個單獨的對象使用「異構集合」模式,但我不認爲在這種情況下,並沒有涉及到我的問題。

package util; 

import java.util.Map; 
import java.util.concurrent.ConcurrentHashMap; 

public class CMSObjectCache { 
    static Map<String, CMSObject> cachedCMSObject = new ConcurrentHashMap<String, CMSObject>(); 

    public static void putCachedCMSObject(String cmsKey, CMSObject cmsObject) { 
     cachedCMSObject.put(cmsKey, cmsObject); 
    } 

    public static Object getCachedCMSObject(String objectKey, Class<?> clazz) { 
     CMSObject c2 = cachedCMSObject.get(objectKey); 
     return c2.getCMSObject(Integer.class); // return generic type ? 
    } 

    public static void main(String[] args) { 
     CMSObject cmsObject; 

     // put object of type Integer with key "Int:3" 
     putCachedCMSObject("Int:3", new CMSObject(Integer.class, 3)); 

     // Get that object from the cache 
     Integer i3 = (Integer) getCachedCMSObject("Int:3", Integer.class); // necessary? 
     System.out.println(i3); 
    } 
} 

這是CMSObject樣子(從布洛赫)。

package util; 

import java.util.HashMap; 
import java.util.Map; 

public final class CMSObject { 
    private Map<Class<?>, Object> cmsObject = new HashMap<Class<?>, Object>(); 

    public CMSObject() { 
    } 

    public <T> CMSObject(Class<T> type, T instance) { 
     this.putCMSObject(type, instance); 
    } 

    public <T> void putCMSObject(Class<T> type, T instance) { 
     if (type == null) { 
      throw new NullPointerException("Type is null"); 
     } 
     cmsObject.put(type, instance); 
    } 

    public <T> T getCMSObject(Class<T> type) { 
     return type.cast(cmsObject.get(type)); 
    } 
} 
+0

'CMSObject'的定義是什麼? –

回答

2

這是你的問題還不太清楚,但我只能假設你是前往這樣的事:

class CMSObject{ 
    public <T> T getCMSObject(Class<T> klass) { 
     //... 
    } 
} 

然後你的外在方法應該是有點像

public static <T> T getCachedCMSObject(String objectKey, Class<T> clazz) { 
    CMSObject c2 = cachedCMSObject.get(objectKey); 
    return c2.getCMSObject(clazz); // return generic type ? 
} 
+0

這個技巧。乾杯! – EdgeCase