当前位置: 首页 > 图灵资讯 > 技术篇> 使用 Java 泛型创建 CSV 到对象的转换器

使用 Java 泛型创建 CSV 到对象的转换器

来源:图灵教育
时间:2025-09-02 16:48:41

使用 java 泛型创建 csv 到对象的转换器

本文将介绍如何使用它 Java 创建一个通用的泛型 CSV 文件到 Java 对象转换器。通过泛型,我们可以避免为每个需要转换的类别编写重复的代码,以实现代码的重用和简化。本文将提供示例代码,并讨论一些关于代码设计和最佳实践的建议,以及如何选择合适的代码 CSV 解析库。

泛型 CSV 工具类

使用 Java 泛型可以创建一个通用的 CSV 用于将领的工具类 CSV 将文件转换为不同类型的文件 Java 对象列表。以下是基本列表。 CsvUtils 类的示例:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CsvUtils<T> {

    public List<T> read(String fileName, Class<T> clazz) throws IOException, ReflectiveOperationException {
        List<T> objectList = new ArrayList<>();
        Path pathToFile = Paths.get(fileName);

        try (BufferedReader br = Files.newBufferedReader(pathToFile)) {
            String line = br.readLine(); // Skip header line
            while ((line = br.readLine()) != null) {
                String[] attributes = line.split(",");
                T obj = createObject(attributes, clazz);
                objectList.add(obj);
            }
        }

        return objectList;
    }

    private T createObject(String[] attributes, Class<T> clazz) throws ReflectiveOperationException {
        // This is a basic implementation. Consider using a more robust approach, like reflection.
        // Also consider using a CSV parsing library.
        T obj = clazz.getDeclaredConstructor().newInstance();
        // Assuming the class has a constructor with no arguments.
        // And assuming the class has setters for each attribute in the CSV file.
        // The order of the attributes in the CSV file must match the order of the setters in the class.
        // This is a very simple example and should be improved for real-world use.
        if (attributes.length > 0) {
            try {
                clazz.getMethod("setId", int.class).invoke(obj, Integer.parseInt(attributes[0]));
            } catch (NoSuchMethodException e) {
                // Handle exception, e.g., if the class does not have an setId method
            }
        }
        if (attributes.length > 1) {
            try {
                clazz.getMethod("setName", String.class).invoke(obj, attributes[1]);
            } catch (NoSuchMethodException e) {
                // Handle exception, e.g., if the class does not have a setName method
            }
        }
        return obj;
    }
}

这个例子中,CsvUtils 泛型类型用于类型 T。 read 方法接受文件名和类型 Class<T> 并返回作为参数 T 对象列表的类型。 createObject 方法负责将 CSV 行转换为 T 类型对象。

使用示例

以下是如何使用的 CsvUtils 类的示例:

立即学习“Java免费学习笔记(深入);

import java.io.IOException;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException, ReflectiveOperationException {
        CsvUtils<Dog> dogCsvUtils = new CsvUtils<>();
        List<Dog> myDogs = dogCsvUtils.read("MyDogs_V1.csv", Dog.class);

        for (Dog dog : myDogs) {
            System.out.println(dog);
        }

        CsvUtils<Cat> catCsvUtils = new CsvUtils<>();
        List<Cat> myCats = catCsvUtils.read("MyCats_V1.csv", Cat.class);

        for (Cat cat : myCats) {
            System.out.println(cat);
        }
    }
}

在这个例子中,我们创建了它 CsvUtils<Dog> 和 CsvUtils<Cat> 例子,分别用它们读取 "MyDogs_V1.csv" 和 "MyCats_V1.csv" 文件。

注意事项
  • 错误处理: 在实际应用中,有必要处理可能发生的事情 IOException 其他异常,如文件不存在、格式错误等。
  • CSV 解析库: 手动解析 CSV 字符串容易出错,建议使用成熟的字符串 CSV 例如,分析库 Apache Commons CSV、OpenCSV 或 Jackson CSV。 这些库提供了更强大、更灵活的库 CSV 解析功能。
  • 对象创建: createObject 该方法的实现取决于具体的类结构。 构造函数或工厂方法可以通过反射动态创建对象并设置属性。
  • 类型转换: CSV 文件中的数据是字符串类型,需要根据目标对象的属性类型进行转换。 例如,将字符串转换为整数、日期等。
  • Header 处理: 在 CSV 通常第一行是文件中的第一行 Header,需要跳过。
  • 健壮的代码: 上述代码示例只是一个简单的演示,在实际应用中,需要考虑更多的边界情况和错误处理。
使用 CSV 解析库

以下是使用 Apache Commons CSV 库的示例:

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CsvUtils<T> {

    public List<T> read(String fileName, Class<T> clazz) throws IOException, ReflectiveOperationException {
        List<T> objectList = new ArrayList<>();
        try (
            Reader reader = Files.newBufferedReader(Paths.get(fileName));
        ) {
            Iterable<CSVRecord> records = CSVFormat.DEFAULT
                    .withHeader("Id","Name") //define header names
                    .withFirstRecordAsHeader()
                    .parse(reader);

            for (CSVRecord record : records) {
                T obj = createObject(record, clazz);
                objectList.add(obj);
            }
        }

        return objectList;
    }

    private T createObject(CSVRecord record, Class<T> clazz) throws ReflectiveOperationException {
        // This is a basic implementation. Consider using a more robust approach, like reflection.
        // Also consider using a CSV parsing library.
        T obj = clazz.getDeclaredConstructor().newInstance();
        // Assuming the class has a constructor with no arguments.
        // And assuming the class has setters for each attribute in the CSV file.
        // The order of the attributes in the CSV file must match the order of the setters in the class.
        // This is a very simple example and should be improved for real-world use.
        try {
            clazz.getMethod("setId", int.class).invoke(obj, Integer.parseInt(record.get("Id")));
        } catch (NoSuchMethodException e) {
            // Handle exception, e.g., if the class does not have an setId method
        }
        try {
            clazz.getMethod("setName", String.class).invoke(obj, record.get("Name"));
        } catch (NoSuchMethodException e) {
            // Handle exception, e.g., if the class does not have a setName method
        }
        return obj;
    }
}

我们在这个例子中使用它 CSVFormat 类来配置 CSV 并使用分析器 CSVRecord 类来访问 CSV 行中的数据。

总结

通过使用 Java 泛型和 CSV 我们可以创建一个通用的分析库 CSV 文件到 Java 对象转换器避免为每个需要转换的类编写重复的代码。在实际应用中,需要根据具体需要选择合适的代码 CSV 分析库和对象创建方法,并处理可能出现的异常。 此外,为了提高代码的可维护性和可扩展性,应尽量避免硬编码,而是使用配置文件或注释来指定 CSV 文件和 Java 对象之间的映射关系。

以上就是使用 Java 泛型创建 CSV 关于对象转换器的详细信息,请关注图灵教育的其他相关文章!