BeanUtils工具类使用示例说明
下文笔者讲述BeanUtils工具类简介说明,如下所示
BeanUtils工具类简介
BeanUtils常用于对象复制,对象转换 如:BeanUtils.copyProperties(Object source, Object target) 如:我们可借助BeanUtils.copyProperties 实现类的转换例:工具类的编写
package com.java265.pojo.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.util.CollectionUtils; import java.util.Arraylist; import java.util.List; import java.util.Objects; public class ConvertUtils { private static Logger LOG = LoggerFactory.getLogger(ConvertUtils.class); private ConvertUtils() { } public static <S, T> T convert(S sourceObject, Class<T> targetClass) { if (Objects.isNull(sourceObject)) { return null; } T targetObject = null; try { targetObject = targetClass.newInstance(); } catch (Exception e) { LOG.error("object convert error : {}", e.getMessage()); } BeanUtils.copyProperties(sourceObject, targetObject); return targetObject; } public static <S, T> ArrayList<T> convertList(List<S> sourceList,Class<T> targetClass) { if (CollectionUtils.isEmpty(sourceList)) { return null; } ArrayList<T> targetList = new ArrayList<>(); for (int index = 0; index < sourceList.size(); index++) { T targetObject = null; try { targetObject = targetClass.newInstance(); } catch (Exception e) { LOG.error("object convert error : {}", e.getMessage()); } BeanUtils.copyProperties(sourceList.get(index),targetObject); targetList.add(targetObject); } return targetList; } }应用示例
ConvertUtils.convertList(model, Test.class);//即可实现model对象转换为Test //List转换 ConvertUtils.convertList(modelList,Test.class);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。