如何重构这些包装方法以消除重复的代码?
以下两种方法用于使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Class
实现了接口Type
,因此看起来只需第一个方法就足够了。编辑:实际上,这些方法看起来像是出于某种原因而单独实现的。至少阅读javadoc 以在重构之前了解原因。感谢家指出了这一点。
Class
implements the interfaceType
, 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.
Type
是由Class
实现的接口,因此您可以完全摆脱第二种方法。Type
is an interface implemented byClass
, so you could get rid of the second method completely.