给定以下 Java 代码:
public class Test {
public static class A<T> {
private T t;
public A(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static class B<T> {
private T t;
public B(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static class F<T> {
private T t;
public F(T t) {
this.t = t;
}
public A<B<T>> construct() {
return new A<>(new B<>(t));
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public static void main(String[] args) {
F<?> f = new F<>(0);
// 1: KO
// A<B<?>> a = f.construct();
// 2: KO
// A<B<Object>> a = f.construct();
// 3: OK
// A<?> a = f.construct();
}
}
在Test
类的主要方法中,将接收结果的变量的正确类型是f.construct()
什么?这种类型应该类似于我正在寻找的A<B<...>>
地方。...
上面有 3 行注释的代码代表了我解决这个问题的尝试。第一行和第二行无效。第三个是,但我丢失了B
类型信息,我必须强制转换a.getT()
。