如果在Java中创建泛型类(该类具有泛型类型参数),您可以使用泛型方法(该方法采用泛型类型参数)吗?
请考虑以下示例:
public class MyClass {
public <K> K doSomething(K k){
return k;
}
}
public class MyGenericClass<T> {
public <K> K doSomething(K k){
return k;
}
public <K> List<K> makeSingletonList(K k){
return Collections.singletonList(k);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所期望的泛型方法,我可以调用任何对象的doSomething(K)实例MyClass:
MyClass clazz = new MyClass();
String string = clazz.doSomething("String");
Integer integer = clazz.doSomething(1);
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使用MyGenericClass 没有指定泛型类型的实例,我调用doSomething(K)返回一个Object,无论K传入什么:
MyGenericClass untyped = new MyGenericClass();
// this doesn't compile - "Incompatible types. Required: String, Found: Object" …Run Code Online (Sandbox Code Playgroud) 为什么
class Foo<T> {
}
class Bar<T> {
List<Foo<?>> getFoos() {
return null;
}
}
class Baz {
void baz(Bar bar) {
for (Foo foo : bar.getFoos());
// ^
//error: incompatible types: Object cannot be converted to Foo
}
}
Run Code Online (Sandbox Code Playgroud)
给出编译器错误
class Foo<T> {
}
// changed Bar<T> to Bar
class Bar {
List<Foo<?>> getFoos() {
return null;
}
}
class Baz {
void baz(Bar bar) {
for (Foo foo : bar.getFoos());
}
}
Run Code Online (Sandbox Code Playgroud)
和
class Foo<T> {
}
class …Run Code Online (Sandbox Code Playgroud) 请按顺序阅读代码中的注释,问题详情如下.
为什么会发生这种差异?
如果可能,请引用JLS.
import java.util.*;
/**
* Suppose I have a generic class
* @param <T> with a type argument.
*/
class Generic<T> {
// Apart from using T normally,
T paramMethod() { return null; }
// the class' interface also contains Generic Java Collections
// which are not using T, but unrelated types.
List<Integer> unrelatedMethod() { return null; }
}
@SuppressWarnings("unused")
public class Test {
// If I use the class properly (with qualified type arguments)
void properUsage() { …Run Code Online (Sandbox Code Playgroud)