有了bean工具類,List相互轉換 對象轉換就簡單多了:
列如:
-- List相互轉換
//查詢數據
List<RightsCoupon> fileList=this.query().eq("id",id).eq("active_flag",EnumConstant.IsActive.True.getValue()).orderBy(true, true, "sort").list();
//定義一個實體類 RightsCouponDto
List<RightsCouponDto> rightsCouponList = BeanUtil.convertListToList(rightsCouponDtoList, new TypeReference<List<RightsCouponDto>>() {});
-- 對象相互轉換
//查詢出數據
TMemberBasic basic = memberBasicService.getById(id);
//定義一個實體類(字段和類型跟TMemberBasic裏要一樣)
UseDto useDto = new UseDto();
BeanUtils.copyProperties(basic,useDto );
bean工具類:
package com.ebj.wwk.core.toolbox.utils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* bean工具類
*/
@Slf4j
public class BeanUtil {
/**
* 複製 2個bean的屬性值
* @param source
* @param target
* @param propertiesNames
*/
public static void copyProperties(Object source,Object target,List<String> propertiesNames){
// 如果屬性列表不存在,將把 source的所有屬性設置爲屬性列表
if (propertiesNames==null || propertiesNames.size() == 0){
Arrays.stream(source.getClass().getDeclaredFields()).forEach(it->{
try {
target.getClass().getDeclaredField(it.getName()).set(target,it.get(source));
}catch (Exception e){
log.warn(e.getMessage());
}
});
}else {
propertiesNames.forEach(it->{
try {
Field fd = source.getClass().getDeclaredField(it);
target.getClass().getDeclaredField(it).set(target,fd.get(source));
}catch (Exception e){
log.warn(e.getMessage());
}
});
}
}
/**
* 判斷 當前屬性是否存在 此 對象中
* @param obj
* @param propName
* @return
*/
public static Boolean checkProperties(Object obj,String propName){
try {
obj.getClass().getDeclaredField(propName);
return true;
}catch (Exception e){
return false;
}
}
/**
* 設置 對象中 屬性的值
* @param obj
* @param propName
* @param val
*/
public static void setProperties(Object obj,String propName,Object val){
try {
Field filed=obj.getClass().getDeclaredField(propName);
filed.setAccessible(true);
if(filed.getGenericType() instanceof List||filed.getGenericType() instanceof ParameterizedType){
filed.set(obj,JSON.parseObject(val.toString(),filed.getType()));
}else {
filed.set(obj,val);
}
}catch (Exception e){
log.warn(e.getMessage());
}
}
/**
* 轉換 對象名稱,去掉第一個"T" 字符
* 例如 convertBeanName(TUserBasic.class,":") TUserBasic -> user:basic
* @param obj
* @param separator
* @return
*/
public static String convertBeanName(Object obj,String separator){
String className = obj.getClass().getSimpleName();
// 獲取第一個字符,判斷是否是"T"
String firstChar = className.substring(0,1);
if (firstChar.equals("T")){
className = className.substring(1,className.length());
}
StringBuilder resString = new StringBuilder();
Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
Matcher matcher = pattern.matcher(className);
while (matcher.find()) {
String word = matcher.group();
resString.append(word.toUpperCase());
resString.append(matcher.end() == className.length() ? "" : separator);
}
return resString.toString();
}
/**
* 對象轉換
*/
public static <T> T ObjectToObject(Object source,Class<T> target){
try {
return JSON.parseObject(JSON.toJSONString(source),target);
}catch (Exception e){
return null;
}
}
/*
*列表對象轉換
*/
public static <T> List<T> convertListToList(List bList, TypeReference typeRef) {
if (bList == null) return null;
ObjectMapper objectMapper = new ObjectMapper();
List<T> list = null;
try {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
list = objectMapper.readValue(objectMapper.writeValueAsString(bList), typeRef);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static Field getDeclaredField(Object object, String fieldName){
Field field = null ;
Class<?> clazz = object.getClass() ;
for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName) ;
return field ;
} catch (Exception e) {
//這裏甚麼都不能拋出去。
//如果這裏的異常打印或者往外拋,則就不會進入
}
}
return null;
}
/**
* 直接讀的屬性值, 忽略 private/protected 修飾符, 也 * @param object : 子類對象
* @param fieldName : 父類中 * @return : 父類中 */
public static Object getFieldValue(Object object, String fieldName){
//根據 對象和屬性名通過取 Field對象
Field field = getDeclaredField(object, fieldName) ;
//抑制Java對其的檢查
field.setAccessible(true) ;
try {
//獲的屬性值
return field.get(object) ;
} catch(Exception e) {
e.printStackTrace() ;
}
return null;
}
}