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

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参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容