2

As per title, why List<MyType>.class doesn't work? How do I get the class for this type (to pass to a function as a type param).

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
gotch4
  • 12,473
  • 27
  • 100
  • 161
  • You might find this article http://docs.oracle.com/javase/tutorial/java/generics/erasure.html and this question useful http://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens – Gyan aka Gary Buyn Feb 01 '12 at 23:50

4 Answers4

1

In Java, List<MyType>.class is List.class. The two are equivalent due to something called "type erasure".

luiscubal
  • 23,581
  • 8
  • 51
  • 82
  • yes, but sometimes the generic type is needed, for example json deserialization. Gson handles it like this: http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener – Kevin Feb 01 '12 at 23:52
  • The concept of "generic type" simply does not exist on the JVM(runtime). Generic information is erased - destroyed - when the code is compiled. – luiscubal Feb 01 '12 at 23:55
  • @Kevin In other words, TypeToken is an extension - not part of Java itself. It is a workaround. – luiscubal Feb 01 '12 at 23:58
  • @luiscubal: That's not entirely true. Generic types do exist at runtime as part of class and method signatures. See java.lang.reflect.ParameterizedType – Michael Borgwardt Feb 02 '12 at 00:02
  • @MichaelBorgwardt I suppose that makes sense, since Java compilers known about that sort of thing. But that distinction does not matter for the purposes of this particular question(since IIRC `.class` does not appear in class/method signatures) – luiscubal Feb 02 '12 at 00:43
1

Java generics are based on type erasure - type parameters to individual objects don't exist at runtime. If you describe what you specifically want to achieve, we may be able to come up with a workaround.

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
  • I think he wants to pass that class to a reflective function as a type param. He should be all set - just pass List.class. – user949300 Feb 01 '12 at 23:54
0

You also might want to indicate that the conventions implied by generics are enforced at compile time. The compiler performs the right casts, checks types, and then type erasure occurs.

ncmathsadist
  • 4,227
  • 3
  • 26
  • 40
0

The solution for Google GSon Library is to use TypeToken:

 Type a = new TypeToken<List<MyClass>>() {}.getType();
gotch4
  • 12,473
  • 27
  • 100
  • 161