Java generics - obtaining actual type of generic parameter

后端 未结 3 911
遇见更好的自我
遇见更好的自我 2020-12-12 01:14

I have read Get type of a generic parameter in Java with reflection post and it made me wonder how that would be possible. I used the solution that someone posted and using

3条回答
  •  青春惊慌失措
    2020-12-12 01:47

    The code you use only works in some very specific cases, where the actual type parameter is known (and stored) at compile time.

    For example if you did this:

    class IntegerList extends ArrayList {}
    
    List l = new IntegerList();
    

    In this case the code you showed would actually return Integer.class, because Integer is "baked into" the IntegerList.

    Some libraries (ab)use this trick via the use of type tokens. See for example the GSON class TypeToken:

    Represents a generic type T. You can use this class to get the generic type for a class. > For example, to get the generic type for Collection, you can use:

    Type typeOfCollectionOfFoo = new TypeToken>(){}.getType()
    

    This works because the anonymous class created in here has compiled-in the information that its type parameter is Collection.

    Note that this would not work (even if the TypeToken class wouldn't prevent it by making its constructor protected):

    Type typeOfCollectionOfFoo = new TypeToken>().getType()
    

提交回复
热议问题