简体   繁体   English

泛型调用方法

[英]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). 我正在使用可返回可转换为Map的JSON的服务(我正在使用google-gson lib进行转换)。 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: Utils.fromJSON方法:

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. 如您所见,方法getShows()和getUnwatchedEpisodes()具有相同的结构。 Only difference is a parametrized type of the returning Set. 唯一的区别是返回Set的参数化类型。 So, I decided to move getting Set from JSON to util method: 因此,我决定将Set从JSON转移到util方法:

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. 谢谢你的帮助。

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. 也许最简单的方法是将type的type更改为Type ,并传入new TypeToken<Map<String, ProfileShow>>() { }.getType()或类似的名称。

I guess you could construct the ParameterizedType if you really wanted. 我想如果您真的想要的话,可以构造ParameterizedType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM