java实体类间的转换_java 实体类集合转换和实体类转换
1.首先要先創建一個函數式接口接口(@FunctionalInterface),回調方法
@FunctionalInterface
public interface BeanCopyUtilCallBack {
/**
* 定義默認回調方法
* @param t
* @param s
*/
void callBack(S t, T s);
}
2.下面開始創建一個類并繼承BeanUtils工具類,并編寫三個方法
/**
* List集合轉換
*/
public class BeanCopyUtil extends BeanUtils {
/**
* 集合數據的拷貝
* @param sources: 數據源類
* @param target: 目標類::new(eg: UserVO::new)
* @return
*/
public static List copyListProperties(List sources, Supplier target) {
return copyListProperties(sources, target, null);
}
/**
* 帶回調函數的集合數據的拷貝(可自定義字段拷貝規則)
* @param sources: 數據源類
* @param target: 目標類::new(eg: UserVO::new)
* @param callBack: 回調函數
* @return
*/
public static List copyListProperties(List sources, Supplier target, BeanCopyUtilCallBack callBack) {
List 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 T copyPropertiesSet(S sources, Supplier target) {
T t = target.get();
copyProperties(sources, t);
return t;
}
}
3.調用集合轉換方法
List user = new ArrayList<>();
//調用轉換集合
List users = BeanCopyUtil.copyListProperties(user,UserVos::new);
//調用轉換實體類
UserVo user1 =new UserVo();
UserVos users1 = BeanCopyUtil.copyPropertiesSet(user1,UserVos::new);
總結
以上是生活随笔為你收集整理的java实体类间的转换_java 实体类集合转换和实体类转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于C#的ArcEngine二次开发教程
- 下一篇: SVN使用介绍