Duplicate collections and objects

During the development process, there will always be some conversions of BO, PO, DTO, VO, etc., such as converting userVO to userPO. Write your own conversion method as follows

private UserPO converterUser(UserVO user) {
    
    
   UserPO userPO = new UserPO();
   userPO.setId(user.getId());
   // add more feild...
   return userPO;
}

This is the most original and the most labor-intensive. A bug was created if a certain field was accidentally written wrong. However, there are ready-made methods in some jar packages that can be used directly. For example, BeanUtils.copyProperties(source,target);the source code in the spring-beans package is as follows,
insert image description here
so write the tool class as follows

package com.yulisao.utils;


import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class ConverterUtil {
    
    

    /**
     * 复制对象
     */
    public static <T,K> T convert(K source, Class<T> clazz) {
    
    
        T t = BeanUtils.instantiate(clazz);
        BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 复制集合
     */
    public static <T,K> List<T> convertList(List<K> sourceList, Class<T> clazz) {
    
    
        if (CollectionUtils.isEmpty(sourceList)) {
    
    
            return null;
        }

        ArrayList<T> target = new ArrayList<>();
        sourceList.forEach(k -> target.add(convert(k, clazz)));
        return target;
    }
}

The calling example is as follows

public static void main(String[] args) {
    
    
        UserVO vo = new UserVO(); // 实际中从数据库查询得到数据
        UserPO po = ConverterUtil.convert(vo, UserPO.class); // 进行转换,最好先判vo是否空
        
        List<UserVO> voList = new ArrayList<>(); // 实际中从数据库查询得到数据
        List<UserPO> poList = ConverterUtil.convertList(voList, UserPO.class); // 进行转换,最好先判voList是否空
    }

The two input parameters are source object/source object collection target object.class

Guess you like

Origin blog.csdn.net/qq_29539827/article/details/129987922