Passing the Class in java of a generic list?

前端 未结 4 1087
遇见更好的自我
遇见更好的自我 2020-12-31 06:58

I have a method for reading JSON from a service, I\'m using Gson to do my serialization and have written the following method using type parameters.

public T         


        
相关标签:
4条回答
  • 2020-12-31 07:16

    If you are using SpringFramework you could use ParameterizedTypeReference as follows:

     restClient.getDeserializedJSON(ParameterizedTypeReference<List<MyClass>>(){},url);
    
    0 讨论(0)
  • 2020-12-31 07:19

    As a follow up to this, I found this in the Gson docs.

    Type listType = new TypeToken<List<String>>() {}.getType();
    

    Which solves the problem of getting the type safely but the TypeToken class is specific to Gson.

    0 讨论(0)
  • 2020-12-31 07:20

    You can use Bozho's solution, or avoid the creation of a temporary array list by using:

    Class<List<MyClass>> clazz = (Class) List.class;
    

    The only problem with this solution is that you have to suppress the unchecked warning with @SuppressWarnings("unchecked").

    0 讨论(0)
  • 2020-12-31 07:30

    You can't. You'd have to use unsafe cast:

    Class<List<MyClass>> clazz = 
       (Class<List<MyClass>>) new ArrayList<MyClass>().getClass();
    
    0 讨论(0)
提交回复
热议问题