import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; /** * @author caiyi.yu */ public class ConvertBeanUtil { // 转换单个对象 public static <T, R> R convertBean(T source, Class<R> targetClass) { if (source == null) { return null; } try { R target = targetClass.getDeclaredConstructor().newInstance(); BeanUtils.copyProperties(source, target); return target; } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } } // 转换 List 对象 public static <T, R> List<R> convertListBean(List<T> sourceList, Class<R> targetClass) { if (sourceList == null) { return null; } List<R> targetList = new ArrayList<>(); for (T source : sourceList) { R target = convertBean(source, targetClass); targetList.add(target); } return targetList; } }
Springboot转换Bean工具类
最新推荐文章于 2024-11-17 16:34:30 发布