【问题标题】:Combining several methods into a single generic method将几种方法组合成一个通用方法
【发布时间】:2014-03-17 10:17:01
【问题描述】:

如果我有“n”个这样的方法,有没有办法可以优化它并使其成为一个函数?

或者还有其他更好的选择可以让我更通用吗?

public List<Address> getAddressList(String response) {
    List<Address> AddressList = new ArrayList<Address>();
    if (response != null && response.length() > 0) {
        try {
            Gson gson = new Gson();
            Type collectionType = new TypeToken<List<Address>>(){}.getType();
            AddressList = gson.fromJson(response, collectionType);              
        } catch (IllegalStateException ex) {
        } catch (Exception ex) {
        }
    }
    return AddressList;
}

public List<Tweet> getTweetList(String response) {
    List<Tweet> tweetList = new ArrayList<Tweet>();
    if (response != null && response.length() > 0) {
        try {
            Gson gson = new Gson();
            Type collectionType = new TypeToken<List<Tweet>>(){}.getType();
            tweetList = gson.fromJson(response, collectionType);                
        } catch (IllegalStateException ex) {
        } catch (Exception ex) {
        }
    }
    return tweetList;
} 

【问题讨论】:

标签: java gson


【解决方案1】:

this here question复制axtavt的答案:


如果不将T(如Class&lt;T&gt;)的实际类型传递给您的方法,则无法做到这一点。

但如果你明确传递它,你可以为List&lt;T&gt;创建一个TypeToken,如下所示:

private <T> List<T> GetListFromFile(String filename, Class<T> elementType) {
    ...
    TypeToken<List<T>> token = new TypeToken<List<T>>() {}
        .where(new TypeParameter<T>() {}, elementType);
    List<T> something = gson.fromJson(data, token);
    ...
}

另请参阅:


所以,要回答你的问题,你可以这样做:

public List<Address> getAddressList(final String response) {
    return getGenericList(response, Address.class);
}

public List<Tweet> getTweetList(final String response) {
    return getGenericList(response, Tweet.class);
}

@SuppressWarnings("serial")
private <T> List<T> getGenericList(final String response, final Class<T> elementType) {
    List<T> list = new ArrayList<T>();
    if (response != null && response.length() > 0) {
        try {
            final Gson gson = new Gson();
            final Type collectionType = 
                    new TypeToken<List<T>>(){}.where(new TypeParameter<T>() {}, elementType).getType();
            list = gson.fromJson(response, collectionType);
        }
        catch (final IllegalStateException ex) {
        }
        catch (final Exception ex) {
        }
    }
    return list;
}

编辑:尝试了代码

我通过以下小测试尝试了这段代码,它应该只创建一个包含几个地址的列表:

public static void main(final String[] args) {
    final List<Address> addressList = getAddressList("[{}, {}]");
    System.out.println(addressList);
}

输出是:

[gson.Address@6037fb1e, gson.Address@7b479feb]

我在我的测试项目中创建了自己的 Address 类,因此在上面的输出中使用了 gson.Address。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多