拷贝vo对象
一些查询到的数据很多是不需要的,可以创建vo对象,对需要的对象属性进行拷贝
maven依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> <scope>provided</scope> </dependency>
封装好的BeanUtil工具类
vo对象的字段名要跟源对象的一样
package com.seacoders.weigh.commons; import com.seacoders.weigh.commons.exception.BeanCopyException; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; /** * @author * @date * * 对Spring BeanUtils扩展,支持List集合拷贝 */ public class BeanUtil { public static void copyProperties(Object source, Object target) { BeanUtils.copyProperties(source, target); } /** * 拷贝Bean对象 * @param source 源对象 * @param clazz 目标对象额Class * @param <T> * @return */ public static <T> T copyProperties(Object source, Class<T> clazz){ Object target = null; try { target = clazz.newInstance(); copyProperties(source, target); return (T)target; } catch (InstantiationException e) { throw new BeanCopyException(e.getMessage()); } catch (IllegalAccessException e) { throw new BeanCopyException(e.getMessage()); } } /** * 拷贝List集合 * @param source 源对象集合 * @param clazz 目标对象Class * @param <T> * @return */ public static <T> List<T> copyListProperties(List source, Class<T> clazz) { List<T> list = new ArrayList<>(); for (Object o : source) { Object target = copyProperties(o, clazz); list.add((T)target); } return list; } }
原文地址:https://www.cnblogs.com/ssjf/p/10177842.html
时间: 2024-10-17 15:09:55