Why is this not possible?
List<Foo>.class
Or more specifically let A
be a class with a type parameter (i.e. class A<T> { // code }
why is new A<T>().getClass()
possible while A<Foo>.class
a compiler error?
Why is this not possible?
List<Foo>.class
Or more specifically let A
be a class with a type parameter (i.e. class A<T> { // code }
why is new A<T>().getClass()
possible while A<Foo>.class
a compiler error?
In generics, the part within < and > is just an option for the Generic class.
In your example, the class is List, so you would type List.class (or list.getClass() if it's instantiated)
List<T> is just a List, with exactly the same class. T is only used by the compiler to check for consistency.
new A<T>().getClass()
returns the exact same object as A.class
. Class
objects represent raw types without generic information. A<T>.class
would just be lying as to what it actually represents, so it is not allowed.
I think this is a fair question.
This works fine:
Class c = new ArrayList().getClass();
c= ArrayList.class;
This does not:
c = new ArrayList<String>().getClass(); // still ok
c = ArrayList<String>.class; // compilation fails
The result would always be the same with or without the generic type.
This new ArrayList<String>().getClass()
does not bring anything more compared to new ArrayList().getClass()
and it is accepted.
This ArrayList<String>.class
does not bring anything more compared to ArrayList.class
and it is not.
So, why?
Probably it is the compiler doing its best to prevent us from writing useless code.