返回通用对象

时间:2012-05-29 17:49:10

标签: java caching

我正在创建一个对象缓存。我在编写一个通用的方法返回类型(请参阅 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的样子(来自Bloch)。

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));
    }
}

1 个答案:

答案 0 :(得分: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 ?
}