Ben Flynn
Ben Flynn

Reputation: 18922

Specifying generic type information through a parameter

I have this code I am refactoring:

    if (response != null) {
        Type collectionType = new TypeToken<List<GameInfo>>() {}.getType();
        Gson gson = new Gson();
        return (List<GameInfo>) gson.fromJson(response, collectionType);
    }

Can I create a function where the "List" part could be any Collection type?

Example of illegal code:

private <T> T collectionFromJson(String pResponseJson, Class<T> pCollectionClass) {
    T result = null;
    Type collectionType = new TypeToken<pCollectionClass>() {
    }.getType();
    ...
    return result;
}

Example of illegal call to illegal code that illustrates what I'm shooting for:

return collectionFromJson(response, List<GameInfo>.class);

Upvotes: 2

Views: 998

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

This isn't going to be possible using a Class<T> argument, since Class only supports representing raw types like List - the type List<GameInfo> cannot be represented by a Class object, which is why TypeToken exists.

Your method would need to take a TypeToken<T> argument instead and leave it up to the caller to create that argument:

private <T extends Collection<U>, U> T collectionFromJson(String pResponseJson, TypeToken<T> typeToken) {
    return (T)new Gson().fromJson(pResponseJson, typeToken.getType());
}

...

TypeToken<List<GameInfo>> typeToken = new TypeToken<List<GameInfo>>() { };
List<GameInfo> lst = collectionFromJson(response, typeToken);

(disclaimer: I only have experience with Java/generics, not GSON)

Upvotes: 2

Related Questions