-1
你能解決我對Josh Blocks有效的Java異構容器所做的事嗎?我正在將string.class存儲在stringClass中,但它不起作用。你能解釋一下爲什麼,並解決它嗎?Typesafe異構容器拼圖
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());
}
}
工程。它與Class <?有什麼不同?擴展字符串>? (也有效) – CandiedOrange 2014-09-04 03:16:22
@CandiedOrange是的,泛型的整體概念有所不同,儘管在Class類層次上有所不同,因爲它使用類型參數。通配符在[更詳細的討論](http://stackoverflow.com/questions/252055/java-generics-wildcards)和[這裏](http://stackoverflow.com/questions/2723397/java-generics-what -is-pecs)等等。 – 2014-09-04 03:20:38