[英]How can I refactor these wrapper methods to get rid of duplicated code?
The following two methods are used to wrap deserialization using Google Gson:以下两种方法用于使用 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?有什么建议么?
Class
implements the interface Type
, so it looks like only having the first method should be sufficient. Class
实现了接口Type
,所以看起来只有第一种方法就足够了。
EDIT: actually it looks like these methods are implemented separately for a reason.编辑:实际上看起来这些方法是单独实现的。 At least read the javadoc to understand why before refactoring.
在重构之前至少阅读javadoc以了解原因。 Thanks to home for pointing this out.
感谢 home 指出这一点。
Type
is an interface implemented by Class
, so you could get rid of the second method completely. Type
是由Class
实现的接口,因此您可以完全摆脱第二种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.