2

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?

fernandohur
  • 6,395
  • 9
  • 44
  • 82
  • see this [answer](http://stackoverflow.com/a/2160974/180100) –  Feb 06 '15 at 15:31
  • 1
    see also: http://stackoverflow.com/questions/2390662/java-how-do-i-get-a-class-literal-from-a-generic-type (cletus answer) –  Feb 06 '15 at 15:31

3 Answers3

2

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.

Calabacin
  • 647
  • 1
  • 8
  • 19
0

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.

Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375
0

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.

Cristian Sevescu
  • 1,094
  • 6
  • 11