有什么办法可以减少代码量吗?

Is there any way to reduce the amount of code?

我一直在做一个学习项目,看起来不错,但我想把它做得尽可能好。我有两个单独的 JSON 文件,包含用户和操作。我需要提取该数据并对其进行一些处理。但问题是关于获取这些数据。我有一个名为 DataReader 的 class,它有两个方法 - 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);
    }
}

如您所见,这两种方法做的事情几乎相同,区别仅在于它 returns 和从 JSON 文件中获取的对象类型。

那么有没有可能制作一个像 readData 这样的方法,它只获取 fileName 参数并自行整理这些东西以减少代码量?

您需要关闭那个 Reader,特别是您正在创建的 FileReader 对象。您也不需要将 Type 定义为局部变量,因为这是不必要的。只是内联它。 您可以对另一种方法执行相同的操作。

        public List<Action> readActionsSimplified(String fileName) throws IOException {
            try (Reader reader = new FileReader(fileName)) {
                return gson.fromJson(reader, new TypeToken<List<Action>>() {}.getType());
            }
        }

也许你可以试试这个。


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);