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