Can you fix what I've done to Josh Blocks Effective Java heterogeneous container? I'm toying with the idea storing String.class in stringClass but it doesn't work. Can you explain why and fix it?
package heterogeneous;
import java.util.HashMap;
import java.util.Map;
//Typesafe heterogeneous container pattern - implementation
public class TypedValue {
private Map<Class<?>, Object> typedValues = new HashMap<Class<?>, Object>();
public <T> TypedValue(Class<T> type, T instance) {
put(type, instance);
}
public <T> T put(Class<T> type, T instance) {
if (type == null)
throw new NullPointerException("Type is null");
@SuppressWarnings("unchecked")
T oldValue = (T) typedValues.put(type, instance);
return oldValue;
}
public <T> T get(Class<T> type) {
return type.cast(typedValues.get(type));
}
// Typesafe heterogeneous container pattern - client
public static void main(String[] args) {
TypedValue j = new TypedValue(String.class, "Java");
TypedValue i = new TypedValue(Integer.class, 0xcafebabe);
TypedValue t = new TypedValue(Class.class, TypedValue.class);
String favoriteString = j.get(String.class);
int favoriteInteger = i.get(Integer.class);
Class<?> favoriteClass = t.get(Class.class);
// .-=== Fix and explain what was wrong ==-. //
Class<?> stringClass = String.class;
//Type mismatch: cannot convert from capture#1-of ? to String
favoriteString = j.get(stringClass);
// ^-=== Fix and explain what was wrong ==-^ //
System.out.printf( "%s %x %s%n",
favoriteString,
favoriteInteger,
favoriteClass.getName() );
}
}