1

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

4

1 回答 1

1

A<? extends B<?>> a = f.construct();正如 Paul Boddington 所说,是正确的语法。

于 2016-03-30T12:36:42.233 回答