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; } }
08-18
3336
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-19
1110
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)