1.首先要先創(chuàng)建一個(gè)函數(shù)式接口接口(@FunctionalInterface)冤吨,回調(diào)方法
@FunctionalInterface
public interface BeanCopyUtilCallBack <S, T> {
/**
* 定義默認(rèn)回調(diào)方法
* @param t
* @param s
*/
void callBack(S t, T s);
}
@FunctionalInterface 函數(shù)式接口詳情
2.下面開(kāi)始創(chuàng)建一個(gè)類(lèi)并繼承BeanUtils工具類(lèi)豪直,并編寫(xiě)三個(gè)方法
/**
* List集合轉(zhuǎn)換
*/
public class BeanCopyUtil extends BeanUtils {
/**
* 集合數(shù)據(jù)的拷貝
* @param sources: 數(shù)據(jù)源類(lèi)
* @param target: 目標(biāo)類(lèi)::new(eg: UserVO::new)
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
return copyListProperties(sources, target, null);
}
/**
* 帶回調(diào)函數(shù)的集合數(shù)據(jù)的拷貝(可自定義字段拷貝規(guī)則)
* @param sources: 數(shù)據(jù)源類(lèi)
* @param target: 目標(biāo)類(lèi)::new(eg: UserVO::new)
* @param callBack: 回調(diào)函數(shù)
* @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) {
// 回調(diào)
callBack.callBack(source, t);
}
}
return list;
}
/**
* 轉(zhuǎn)換實(shí)體類(lèi)
* @param sources 數(shù)據(jù)源類(lèi)
* @param target 目標(biāo)類(lèi)::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.調(diào)用集合轉(zhuǎn)換方法
List<UserVo> user = new ArrayList<>();
//調(diào)用轉(zhuǎn)換集合
List<UserVos> users = BeanCopyUtil.copyListProperties(user,UserVos::new);
//調(diào)用轉(zhuǎn)換實(shí)體類(lèi)
UserVo user1 =new UserVo();
UserVos users1 = BeanCopyUtil.copyPropertiesSet(user1,UserVos::new);