你能解决我对Josh Blocks Effective Java异构容器所做的工作吗?我想在stringClass中存储String.class的想法,但它不起作用。你能解释一下原因并解决它吗?
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() );
}
}
答案 0 :(得分:2)
在这里使用通配符
Class<?> stringClass = String.class;
您明确表示您不了解(关心)基础类型。它可以是任何东西。但是你的方法
favoriteString = j.get(stringClass);
取决于该类型以确定其返回类型。由于它未知,因此返回类型也将推断为?
。您不能将某种未知类型的值分配给String
类型的变量。
将其更改为
Class<String> stringClass = String.class;