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

使用MapStruct映射数组首个元素到目标类遇报错,求解决方案

MapStruct数组首元素映射报错解决方案

你遇到的报错是因为MapStruct不支持直接通过people[0]这种数组下标语法指定源属性。下面提供两种可行的解决方式:

方法一:使用expression属性实现映射

在@Mapping注解中通过expression直接编写Java代码逻辑,获取数组的第一个元素,同时加入空判断避免空指针异常:

@Mapper
public interface MyMapper {
    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    @Mapping(expression = "java(source.getPeople() != null && source.getPeople().length > 0 ? source.getPeople()[0] : null)", target = "person")
    Destination mapToDestination(Source source);
}

方法二:自定义默认处理方法

在Mapper接口中添加一个默认方法,专门处理数组首元素的获取逻辑,再通过映射注解指定使用这个方法:

@Mapper
public interface MyMapper {
    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    @Mapping(source = "source", target = "person", qualifiedByName = "getFirstPerson")
    Destination mapToDestination(Source source);

    @Named("getFirstPerson")
    default Person getFirstPerson(Source source) {
        if (source == null || source.getPeople() == null || source.getPeople().length == 0) {
            return null;
        }
        return source.getPeople()[0];
    }
}

两种方法都能实现将Source中people数组的第一个元素映射到Destination的person属性,建议根据代码风格选择合适的方式,同时务必保留空判断逻辑,防止数组为空或长度为0时出现运行时异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:26:06