Class CsvBinder

java.lang.Object
cloud.opencode.base.csv.bind.CsvBinder

public final class CsvBinder extends Object
CSV Binder - Object binding between CSV data and Java objects CSV绑定器 - CSV数据和Java对象之间的对象绑定

Provides bidirectional mapping between CSV documents and Java objects, supporting both Java Records and traditional POJOs. Uses annotation-based configuration via CsvColumn and CsvFormat for flexible mapping.

提供CSV文档和Java对象之间的双向映射,支持Java Record和传统POJO。 通过 CsvColumnCsvFormat 注解进行灵活映射配置。

Features | 主要功能:

  • Java Record binding via canonical constructor - 通过规范构造函数绑定Java Record
  • POJO binding via setters or direct field access - 通过setter或直接字段访问绑定POJO
  • @CsvColumn for custom column name/index mapping - @CsvColumn自定义列名/索引映射
  • @CsvFormat for date/number pattern formatting - @CsvFormat日期/数字格式化
  • Required field validation - 必填字段验证
  • Automatic type conversion (primitives, BigDecimal, dates, enums) - 自动类型转换

Usage Examples | 使用示例:

// Bind CSV to Records
List<PersonRecord> people = CsvBinder.bind(doc, PersonRecord.class);

// Bind CSV to POJOs
List<Person> people = CsvBinder.bind(doc, Person.class);

// Convert objects to CSV
CsvDocument doc = CsvBinder.fromObjects(people, Person.class);

Security | 安全性:

  • Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
  • Null-safe: Yes (validates inputs) - 空值安全: 是(验证输入)
Since:
JDK 25, opencode-base-csv V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • bind

      public static <T> List<T> bind(CsvDocument doc, Class<T> type)
      Binds CSV document rows to Java objects 将CSV文档行绑定到Java对象

      Supports both Record types (via canonical constructor) and POJOs (via no-arg constructor + setters/field access).

      支持Record类型(通过规范构造函数)和POJO(通过无参构造函数+setter/字段访问)。

      Type Parameters:
      T - the target type | 目标类型
      Parameters:
      doc - the CSV document | CSV文档
      type - the target type | 目标类型
      Returns:
      list of bound objects | 绑定的对象列表
      Throws:
      CsvBindException - if binding fails | 如果绑定失败
    • fromObjects

      public static <T> CsvDocument fromObjects(Collection<T> objects, Class<T> type)
      Converts a collection of Java objects to a CSV document 将Java对象集合转换为CSV文档

      Extracts headers from field names or CsvColumn annotations, and values via getter methods or field access.

      从字段名或 CsvColumn 注解提取标题,通过getter方法或字段访问提取值。

      Type Parameters:
      T - the object type | 对象类型
      Parameters:
      objects - the objects to convert | 要转换的对象
      type - the object type | 对象类型
      Returns:
      the CSV document | CSV文档
      Throws:
      CsvBindException - if conversion fails | 如果转换失败