Home >Java >javaTutorial >How Can I Dynamically Create a Typed ArrayList in Gson Using Reflection?
In this inquiry, the goal is to create a dynamically typed ArrayList using Gson, where the datatype is determined at runtime using Java reflection.
The initial approach involved using a TypeToken to specify the desired type of the ArrayList. However, it resulted in a runtime error.
To resolve this issue, the revised solution leverages the new TypeToken method getParameterized(Type rawType, Type... typeArguments) introduced in Gson 2.8.0. This method allows you to create a TypeToken for a specific parameterized type.
The updated code:
private <T> Type setModelAndGetCorrespondingList2(Class<T> type) { return TypeToken.getParameterized(ArrayList.class, type).getType(); }
With this revised solution, you can dynamically create a TypeToken for the desired ArrayList type at runtime using Java reflection and retrieve the corresponding Type through the getType() method.
The above is the detailed content of How Can I Dynamically Create a Typed ArrayList in Gson Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!