springbootJava web

java 实体类集合转换和实体类转换

2021-01-15  本文已影响0人  改变把

1.首先要先创建一个函数式接口接口(@FunctionalInterface),回调方法

@FunctionalInterface
public interface BeanCopyUtilCallBack <S, T> {

    /**
     * 定义默认回调方法
     * @param t
     * @param s
     */
    void callBack(S t, T s);
}

@FunctionalInterface 函数式接口详情

2.下面开始创建一个类并继承BeanUtils工具类,并编写三个方法

/**
 * List集合转换
 */
public class BeanCopyUtil extends BeanUtils {

    /**
     * 集合数据的拷贝
     * @param sources: 数据源类
     * @param target: 目标类::new(eg: UserVO::new)
     * @return
     */
    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
        return copyListProperties(sources, target, null);
    }

    /**
     * 带回调函数的集合数据的拷贝(可自定义字段拷贝规则)
     * @param sources: 数据源类
     * @param target: 目标类::new(eg: UserVO::new)
     * @param callBack: 回调函数
     * @return
     */
    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanCopyUtilCallBack<S, T> callBack) {
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            copyProperties(source, t);
            list.add(t);
            if (callBack != null) {
                // 回调
                callBack.callBack(source, t);
            }
        }
        return list;
    }

    /**
     * 转换实体类
     * @param sources 数据源类
     * @param target 目标类::new(eg: UserVO::new);
     * @return
     */
    public static <S, T> T copyPropertiesSet(S sources, Supplier<T> target) {
        T t = target.get();
        copyProperties(sources, t);
        return t;
    }
}

3.调用集合转换方法

List<UserVo> user = new ArrayList<>();
//调用转换集合
List<UserVos> users = BeanCopyUtil.copyListProperties(user,UserVos::new);
//调用转换实体类
UserVo user1 =new UserVo();
UserVos users1 =  BeanCopyUtil.copyPropertiesSet(user1,UserVos::new);

1参考链接

上一篇 下一篇

猜你喜欢

热点阅读