I am creating an object cache. I am having trouble writing a method return type (please see getCachedCMSObject) that is generic, so that I don’t have to cast the return as indicated in the comment. I guess I can live with it, but I’d rather use Generics.
cachedCMSObject is a separate object using a “Heterogeneous Collection” pattern, but I don’t think that matters in this case, and does not relate to my problem.
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);
}
}
This is what CMSObject looks like (from 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));
}
}
It’s not yet clear in your question, but I can only assume you are heading to something like this:
And then your outer method should be somewhat like