强制 Java 泛型参数具有相同的类型
如何实现类似的功能而不会出错?
class A<K> {
void f(K x) {}
}
void foo(A<? extends X> a, X x) {
a.f(x); // AN error: The method f(capture#1-of ? extends X) in the
// type A<capture#1-of ? extends X> is not applicable for the
// arguments (X)
}
我知道它之所以发生,是因为'a'可以是A<“non-X”>的实例,所以它的'f'不能接受X的实例作为参数,但是我怎么能强制参数是同一类型的呢?
下面是更多代码:
测试类:
class Test {
<T> void foo(A<T> a, T x) {
a.f(x); // now it works!
}
}
在某些课程中:
Container<X> container;
public void test() {
X x = new X();
new Test().foo(container.get(), x);
}
下面是容器类:
public class Container<K> {
A<? extends K> get() {
return new A<K>();
}
}