How do I build a Java type object at runtime from a generic type definition and runtime type parameters?

前端 未结 6 1171
无人及你
无人及你 2020-12-05 12:16

Assuming a generic type declaration (Java)

class Foo {
    public T bar;
}

how can I, at runtime, instantiate a Type object that r

6条回答
  •  星月不相逢
    2020-12-05 12:31

    It appeared to be really simpler than most people thought:

    Type collectionType = new TypeToken>(){}.getType();
    ArrayList persons = gson.fromJson(response, collectionType);
    

    No need to copy ParameterizedTypeImpl class as newacct suggested.

提交回复
热议问题