嵌套通配符泛型变量做作



给定以下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()

正如Paul Boddington所说,

A<? extends B<?>> a = f.construct();是正确的语法。

最新更新