对不起,也许这是一个愚蠢的问题,但我找不到答案。
方法上的两个泛型参数,一个可以扩展另一个吗?
public class A {
}
public class B extends A {
}
public class C {
}
public class Foo {
public static <R extends A> void f1 (A t, R r){
}
// T and R are generics parameter, R bounds on T
public static <T, R extends T > void f2(T t, R r) {
}
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
Foo.f1(a, b); // no error
Foo.f1(a, c); // compile error, it's ok
Foo.f2(a, b); // no error
Foo.f2(a, c); // no error ! why?
}
}
最后的f2
方法调用没有编译错误,但我认为C
不是A
的子类,应该会出现编译错误。有帮助吗?
最佳答案
因为代码中调用方法的类型参数是隐式的,例如,如果 java 编译器将 T
和 R
推断为 Object
它是很好,不是吗?但是,如果您显式声明它们,则会引发错误:
Foo.<A, C>f2(a, c); //error as you wished
Foo.<Object, Object>f2(a, c); //no errors and it's ok, isn't it?
关于java - 泛型参数扩展了 java 方法的另一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39984548/