如何类似的功能没有错误来实现的?强制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 <“非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>();
}
}
X是类还是类型参数? – Joni