如何重构这些包装方法以消除重复的代码?

发布于 2024-11-29 19:14:18 字数 614 浏览 5 评论 0原文

以下两种方法用于使用 Google Gson 包装反序列化:

public static <T> T Deserialize(String jsonData, Type t) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, t);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

public static <T> T Deserialize(String jsonData, Class<T> toClass) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, toClass);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

它们几乎相同,但我无法找到一种明智的方法来摆脱重复的代码。

有什么建议吗?

The following two methods are used to wrap deserialization using Google Gson:

public static <T> T Deserialize(String jsonData, Type t) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, t);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

public static <T> T Deserialize(String jsonData, Class<T> toClass) {
    T obj = null;

    try {
        obj = new Gson().fromJson(jsonData, toClass);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
    }

    return obj;
}

They are almost identical, but I can't figure out a smart way to get rid of the duplicated code.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑾兮 2024-12-06 19:14:18

Class 实现了接口 Type,因此看起来只需第一个方法就足够了。

编辑:实际上,这些方法看起来像是出于某种原因而单独实现的。至少阅读javadoc 以在重构之前了解原因。感谢家指出了这一点。

Class implements the interface Type, so it looks like only having the first method should be sufficient.

EDIT: actually it looks like these methods are implemented separately for a reason. At least read the javadoc to understand why before refactoring. Thanks to home for pointing this out.

爱*していゐ 2024-12-06 19:14:18

Type 是由 Class 实现的接口,因此您可以完全摆脱第二种方法。

Type is an interface implemented by Class, so you could get rid of the second method completely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文