踩过的坑:使用BeanUtils.copyProperties复制属性,若对象为List需要new数组然后再转成List

    public List<DeliverAddressDTO> selectByUserId(String userId) {
        //根据userId查询
        List<DeliverAddress> deliverAddresses = addressMapper.selectByUserId(userId);
        //new一个长度为entity实体类List.size()的DTO数组
        DeliverAddressDTO[] deliverAddressDTOs = new DeliverAddressDTO[deliverAddresses.size()];
        //把DeliverAddress的属性复制到DTO
        for (int i = 0; i < deliverAddresses.size(); i++) {
            deliverAddressDTOs[i] = new DeliverAddressDTO();
            BeanUtils.copyProperties(deliverAddresses.toArray()[i], deliverAddressDTOs[i]);
        }
        //把DTO数组转换为List
        List<DeliverAddressDTO> deliverAddressDTOS = Arrays.asList(deliverAddressDTOs);

        return deliverAddressDTOS;
    }

在上面的代码中,我需要要把deliverAddresses的属性依次赋值到deliverAddressDTOS中,必须先通过遍历数组复制,否则会报错。遍历过程中,不要忘记new DTO()对象,否则会报java.lang.IllegalArgumentException: Target must not be null异常!

你可能感兴趣的:(Exception,Java)