Nested Generators in Java

Let me ask for an explanation.

Inside the doit () method, I can find out the common nested class In<T>

 public class A { public static class In<T> { } public static <X> void doit() { new In<X>(); } } 

I can, of course, also reach any members of the class In<T>

 public class A { public static class In<T> { public static class Inner<U> { } } public static <X> void doit() { new In.Inner<X>(); } } 

I can still get members of the In<T> class from the doit () method when both classes and methods are nested inside another Container class

 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>(); } } } 

However, making A general, as in

 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>(); } } } 

the compiler throws an error: "A.Container.In member type must be parameterized, since it qualifies as a parameterized type"

Could you give me an explanation?

Note that in previous classes, classes and methods are static.

Note also that creating a generic Container class, as in

 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>(); } } } 

The code is compiling.

And the following code also compiles, where the Container is no longer shared, but the call to the constructor of the Inner<U> class is now more qualified 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>(); } } } 

Thanks.

+7
java generics
source share
1 answer

A nested class that is a member of the static class does not depend on the type parameter (instance) of the class. So in your example

 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 } } } 

There is absolutely no reason for the class instantiation expression

 new In.Inner<X>() 

will result in an error

" A.Container.In member A.Container.In must be parameterized because it is with a parameterized type"

The Inner member type is a nested class In , which is a nested class Container , which is a nested class A None of them has anything to do with the type parameter declared in the declaring class.

This seems like a bug in your IDE, and I'm reporting this as such.

+2
source share

All Articles