Gson TypeToken with dynamic ArrayList item type

前端 未结 9 2170
情深已故
情深已故 2020-11-22 08:55

I have this code:

Type typeOfObjectsList = new TypeToken>() {}.getType();
List objectsList = new Gson().fromJso         


        
9条回答
  •  梦谈多话
    2020-11-22 09:18

    The syntax you are proposing is invalid. The following

    new TypeToken>
    

    is invalid because you're trying to pass a method invocation where a type name is expected.

    The following

    new TypeToken>() 
    

    is not possible because of how generics (type erasure) and reflection works. The whole TypeToken hack works because Class#getGenericSuperclass() does the following

    Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

    If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

    In other words, if it sees ArrayList, that's the ParameterizedType it will return and you won't be able to extract the compile time value that the type variable T would have had.

    Type and ParameterizedType are both interfaces. You can provide an instance of your own implementation.

提交回复
热议问题