You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot用OpenCSV读取CSV遇NoSuchMethodError问题求助

OpenCSV 5.7.1 问题解决方案

1. 解决 NoSuchMethodError 依赖问题

这个错误是因为OpenCSV 5.7.1依赖的Apache Commons Lang3版本不匹配:项目中可能存在低版本的commons-lang3,或者其他依赖引入了低版本,导致找不到FieldUtils.getAllFields方法。

解决步骤:

  • 显式添加兼容版本的commons-lang3依赖(OpenCSV 5.7.1要求版本至少为3.8.1)
  • 若存在依赖冲突,排除其他依赖中的低版本commons-lang3

修改后的Pom依赖示例:

<!-- 优先指定兼容的Commons Lang3版本 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- 或更高兼容版本 -->
</dependency>

<!-- OpenCSV 5.7.1 依赖 -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.7.1</version>
    <!-- 若有冲突,可排除自带的commons-lang3,使用上面指定的版本 -->
    <!--
    <exclusions>
        <exclusion>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </exclusion>
    </exclusions>
    -->
</dependency>

2. 解决泛型警告问题

原代码中CsvToBeanBuilder未指定泛型参数,导致编译器抛出未检查调用警告,添加@SuppressWarnings("rawtypes")无法从根源解决问题。

修改后的核心代码:

public <T> List<T> readFile(Class<T> clazz, MultipartFile file) throws IOException {
    try (InputStream inputStream = file.getInputStream();
         InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
         Reader reader = new BufferedReader(inputStreamReader)) {

        // 给CsvToBeanBuilder指定泛型<T>,消除raw类型警告
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader)
                .withType(clazz)
                .withIgnoreLeadingWhiteSpace(true)
                .withIgnoreEmptyLine(true)
                .build();
        // 无需强制转换,直接返回泛型列表
        return csvToBean.parse();
    } catch (Exception ex) {
        log.error("解析CSV文件出错: ", ex);
        throw new IllegalArgumentException(ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
    }
}

修改后,编译器的未检查调用警告会自动消失,无需依赖@SuppressWarnings注解。

内容的提问来源于stack exchange,提问作者Sahil Bajaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 13:22:06