As an alternative, you could use a small amount of not-type-safe code encapsulated in a way that enforces your constraint:
class Cache {
private Map<Class<?>, Map<Long, ?>> items = new HashMap<Class<?>, Map<Long, ?>>();
private <T> Map<Long, T> getItems(Class<T> type) {
@SuppressWarnings("unchecked")
Map<Long, T> result = (Map<Long, T>) items.get(type);
if (result == null) {
result = new HashMap<Long, T>();
items.put(type, result);
}
return (Map<Long, T>) result;
}
public <T> void addItem(Class<T> type, Long id, T item) {
getItems(type).put(id, item);
}
public <T> T getItem(Class<T> type, Long id) {
return type.cast(getItems(type).get(id));
}
}
The type.cast()
in getItem()
isn't necessary for the compiler to not complain, but it would help catch an object of the wrong type getting into the cache early.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…