java - 有什么办法可以减少代码量?
问题描述
我一直在做一个学习项目,看起来不错,但我想让它尽可能好。我有两个单独的 JSON 文件,包含用户和操作。我需要提取该数据并对其进行一些处理。但问题是关于获取这些数据。我有一个名为 DataReader 的类,它有两种方法——readUsers 和 readActions。
public class DataReader {
Gson gson = new GsonBuilder().setDateFormat("MM.dd").create();
public ArrayList<Action> readActions(String fileName)
throws JsonIOException, JsonSyntaxException, FileNotFoundException {
Type actionsArrayList = new TypeToken<ArrayList<Action>>() {
}.getType();
return gson.fromJson(new FileReader(fileName), actionsArrayList);
}
public HashMap<Integer, User> readUsers(String fileName)
throws JsonIOException, JsonSyntaxException, FileNotFoundException {
Type usersHashMap = new TypeToken<HashMap<Integer, User>>() {
}.getType();
return gson.fromJson(new FileReader(fileName), usersHashMap);
}
}
如您所见,这两种方法做的事情几乎相同,不同之处仅在于它返回和从该 JSON 文件中获取的对象类型。
那么有没有可能制作一个这样的方法readData
,只获取fileName
参数并自行排序以减少代码量?
解决方案
也许你可以试试这个。
public<T> T readData(String fileName,TypeToken<T> typeRef)
throws JsonIOException, JsonSyntaxException, FileNotFoundException {
return gson.fromJson(new FileReader(fileName), typeRef);
}
// make a type class , e.g: MyGsonTypes
public final class MyGsonTypes{
public static final TypeToken<HashMap<Integer, User>> usersHashMapType = new TypeToken<HashMap<Integer, User>>(){}.getType();
}
// when you use it
var data = readData("1.json", MyGsonTypes.usersHashMapType);
推荐阅读
- php - PHP - 逻辑 - if else / or die?
- c - 有人可以向我解释模字符如何输出前导零吗
- c# - 为什么 csproj 中的包引用后来在 PowerShell 模块中不可用?
- azure - 是否有任何 Azure 数据工厂活动来获取 cosmos 集合列表?
- javascript - Discord.js 等待来自作者以外的用户的消息
- swift - CoreData Fetch:获取具有最大一个属性并具有另一个共同属性的对象
- python - 如何在不关闭导入脚本的情况下运行整个 python 脚本?
- python - 减少 django 中的默认复选框大小
- python - 从两个数据帧按数量循环
- javascript - 如何在 react.js 中拥有每 5 秒更改一次的图像?