Java中的嵌套泛型

rve*_*end 7 java generics

请允许我请求解释.

在方法doit()内部,我可以实例化通用嵌套类 In<T>

public class A {

  public static class In<T> {
  }

  public static <X> void doit() {
    new In<X>();
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,我也可以接触到班上的任何成员 In<T>

public class A {

  public static class In<T> {
    public static class Inner<U> {
    }
  }

  public static <X> void doit() {
    new In.Inner<X>();
  }
}
Run Code Online (Sandbox Code Playgroud)

In<T>当类和方法嵌套在另一个类Container中时,我仍然可以从方法doit()到达类的成员

public class A {

  public static class Container {

    public static class In<T> {

      public static class Inner<U> {
      }
    }

    public static <X> void doit() {
      new In.Inner<X>();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,制作A泛型,如

public class A<V> {

  public static class Container {

    public static class In<T> {

      public static class Inner<U> {
      }
    }

    public static <X> void doit() {
      new In.Inner<X>();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编译器除了错误:"成员类型A.Container.In必须参数化,因为它使用参数化类型限定"

请你帮我解释一下吗?

请注意,在之前的代码中,类和方法是静态的.

另请注意,将通用类设为Container,如

public class A<V> {

  public static class Container<Z> {

    public static class In<T> {

      public static class Inner<U> {
      }
    }

    public static <X> void doit() {
      new In.Inner<X>();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

代码编译.

并编译下面的代码,其中Container不再是通用的,但类的构造函数的调用Inner<U>现在更合格Container.In.Inner<X>()

public class A<V> {

  public static class Container {

    public static class In<T> {

      public static class Inner<U> {
      }
    }

    public static <X> void doit() {
      new Container.In.Inner<X>();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Sot*_*lis 1

嵌套类作为static类的成员,不依赖于该类的(实例)类型参数。因此,在你的例子中

class A<V> {

    public static class Container {

        public static class In<T> {

            public static class Inner<U> {
            }
        }

        public static <X> void doit() {
            new In.Inner<X>(); // compilation error
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

类实例创建表达式绝对没有理由

new In.Inner<X>()
Run Code Online (Sandbox Code Playgroud)

会导致错误

“成员类型A.Container.In必须参数化,因为它是用参数化类型限定的”

成员Inner类型是 的嵌套类In,这是 的嵌套类Container,这是 的嵌套类A。它们都与其声明类中声明的类型参数没有任何关系。

这看起来像是您的 IDE 中的一个错误,我会这样报告它。