0

Is it possible to get something similar to Class<List<Data>>.class? I read you can't call .class because of how it works interanlly, so I was wondering if maybe using something similar to new ArrayList<Data>().getClass() might work? That one in particular doesn't work as the returned class is Class<? extends List<Data>> so I'm out of options, is it even possible?

Context: I'm trying to parse a List<Data> using square/moshi but the library seems to be on alpha so there is no documentation on it.

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • 1
    Generics use [Type Erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html). What that basically means is that by the time your code is compiled all of the generics information is gone, and it is no longer available at run time. So, there is no actual difference between a List and a List as far as runtime access (e.g. reflection) is concerned. – Nameless Voice Sep 14 '15 at 17:31
  • It seems that there is a method that accept a `Type` as parameter to create an adapter. You might want to provide it, the same way you can get a type with Gson 's `TypeToken` trick. See also http://stackoverflow.com/questions/30005110/how-does-gson-typetoken-work – Alexis C. Sep 14 '15 at 17:43

1 Answers1

2

There is no Class object that represents List<Data> because generic types are a compile-time feature only. It is possible to make a variable of static type Class<List<Data>> by doing this

Class<List<Data>> clazz = (Class<List<Data>>) (Object) List.class;

You get a compiler warning here. Really clazz is just List.class and the compiler warning is a hint that what you're doing is not a good idea.

There is no Class object representing List<Data> but there is a Type object.

Try this:

public class Main {

    List<String> list;

    public static void main(String[] args) throws Exception {
         // prints java.util.List<java.lang.String>
         System.out.println(Main.class.getField("list").getGenericType());   
    }
}
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • What if instead of `List` it was `List`? I have to pass a `Type` object to a json parser library, and said type should be `List`, so that the library knows it should replace `T` for `Data`. Could it work? – Christopher Francisco Sep 14 '15 at 17:42
  • I just tried it and it said `java.util.List`. To be honest I'm getting dangerously close to the extent of my knowledge on this subject. I agree with Alexis C that you should look into `TypeToken`. – Paul Boddington Sep 14 '15 at 17:45