我不明白为什么这会使编译器感到困惑。我使用泛型类型来保存与and方法T
无关的对象。我一直认为并且在功能上是相同的,但我一定是误会了。编译课程时我得到. 这门课做我所期望的。这里发生了什么?put
get
GenericClass
GenericClass<Object>
DoesntWork
incompatible types - required: String - found: Object
Works
public class GenericClass<T> {
public <V> void put(Class<V> key, V value) {
// put into map
}
public <V> V get(Class<V> key) {
// get from map
return null;
}
public static class DoesntWork {
public DoesntWork() {
GenericClass genericClass = new GenericClass();
String s = genericClass.get(String.class);
}
}
public static class Works {
public Works() {
GenericClass<Object> genericClass = new GenericClass<Object>();
String s = genericClass.get(String.class);
}
}
}