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 的样子(来自 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));
    }
}
4

1 回答 1

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 ?
}
于 2012-05-29T17:54:42.303 回答