ninja
ninja

Reputation: 2968

Calling method with generics

I'm working with a service which returns JSON which can be converted to Map (I'm using google-gson lib for converting). I need to get Set of values from this Map. First, I had the next structure:

public Set<ProfileShow> getShows() {
    String json = ...; //getting JSON from service
    if (!Utils.isEmptyString(json)) {
        Map<String, ProfileShow> map = Utils.fromJSON(json, new TypeToken<Map<String, ProfileShow>>() {
        }.getType());

        Set<ProfileShow> result = new HashSet<ProfileShow>();
        for (String key : map.keySet()) {
        result.add(map.get(key));
        }
        return result;
    }
    return Collections.emptySet();
}

public Set<Episode> getUnwatchedEpisodes() {
    String json = ...; //getting JSON from service
    if (!Utils.isEmptyString(json)) {
        Map<String, Episode> map = Utils.fromJSON(json, new TypeToken<Map<String, Episode>>() {
        }.getType());

        Set<Episode> result = new HashSet<Episode>();
        for (String key : map.keySet()) {
        result.add(map.get(key));
        }
        return result;
    }
    return Collections.emptySet();
}

Utils.fromJSON method:

public static <T> T fromJSON(String json, Type type) {
    return new Gson().fromJson(json, type);
}

As you can see, methods getShows() and getUnwatchedEpisodes() has the same structure. Only difference is a parametrized type of the returning Set. So, I decided to move getting Set from JSON to util method:

public static <T> Set<T> setFromJSON(String json, T type) {
    if (!isEmptyString(json)) {
        Map<String, T> map = fromJSON(json, new TypeToken<Map<String, T>>() {
        }.getType());

        Set<T> result = new HashSet<T>();
        for (String key : map.keySet()) {
        result.add(map.get(key));
        }
        return result;
    }
    return Collections.emptySet();
}

But now I'm stuck how to call this method in a proper way. Something like

Utils.setFromJSON(json, Episode.class.getGenericSuperclass()); //doesn't work

Thanks for your help.

Upvotes: 0

Views: 143

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147124

Perhaps the easiest thing to do is change the type of type to Type, and pass in new TypeToken<Map<String, ProfileShow>>() { }.getType() or similar.

I guess you could construct the ParameterizedType if you really wanted.

Upvotes: 1

Related Questions