我們在開發中,經常需要將一個對象的若干個值賦給另外一個對象的相應字段(類不同,字段名一樣),繼承org.springframework.beans.BeanUtils類,可實現不同類的對象之間相同字段賦值。
public class CopyObjectUtil extends BeanUtils {
private static final Logger logger = LoggerFactory.getLogger(CopyObjectUtil.class);
/**
* 將source中與target類型和名稱相同的屬性,賦值給target的對應屬性,並返回target
*
* @param source 源對象
* @param target 目標對象
* @param ignore 是否忽略空值
*/
public static void copyProperties(Object source, Object target, boolean ignore) {
List<Map<String, Object>> sourceFields = getFieldInfo(source);
if (ObjectUtils.isEmpty(sourceFields)) {
return;
}
for (Map sourceFieldMap : sourceFields) {
try {
Field field = target.getClass().getDeclaredField(sourceFieldMap.get("name").toString());
// 源對象屬性值爲空 或屬性類型不一致 則返回繼續下一條
if (ObjectUtils.isEmpty(sourceFieldMap.get("value")) && ignore) {
continue;
} else if (!sourceFieldMap.get("type").equals(field.getType().toString())) {
continue;
}
field.setAccessible(true);
field.set(target, sourceFieldMap.get("value"));
} catch (Exception ex) {
// 查看目標對象父類屬性
try {
Field superField = target.getClass().getSuperclass()
.getDeclaredField(sourceFieldMap.get("name").toString());
// 源對象屬性值爲空 或屬性類型不一致 則返回繼續下一條
if (ObjectUtils.isEmpty(sourceFieldMap.get("value")) && ignore) {
continue;
} else if (!sourceFieldMap.get("type").equals(superField.getType().toString())) {
continue;
}
superField.setAccessible(true);
superField.set(target, sourceFieldMap.get("value"));
} catch (Exception e) {
logger.error("屬性複製錯誤:", e.getMessage());
}
}
}
}
/**
* 根據屬性名獲取屬性值
*
* @param fieldName
* @param o
* @return
*/
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter);
return method.invoke(o);
} catch (Exception ex) {
// 未找到常規命名的get方法
try {
Method method = o.getClass().getMethod(fieldName);
return method.invoke(o);
} catch (Exception e) {
logger.error("根據屬性名獲取屬性值錯誤:", e.getMessage());
return null;
}
}
}
/**
* 獲取屬性名數組
*/
private static String[] getFieldName(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}
/**
* 獲取屬性類型(type),屬性名(name),屬性值(value)的map組成的list
*/
private static List<Map<String, Object>> getFieldInfo(Object o) {
List<Map<String, Object>> list = new ArrayList<>();
if (ObjectUtils.isEmpty(o)) {
return null;
}
List<Field> fields = new ArrayList<>(Arrays.asList(o.getClass().getDeclaredFields()));
//如果存在父類,獲取父類的屬性值,類型,名稱並添加到一起
Class sc = o.getClass().getSuperclass();
if (sc != null) {
fields.addAll(Arrays.asList(sc.getDeclaredFields()));
}
for (Field field : fields) {
Map<String, Object> infoMap = new HashMap<>();
infoMap.put("type", field.getType().toString());
infoMap.put("name", field.getName());
infoMap.put("value", getFieldValueByName(field.getName(), o));
list.add(infoMap);
}
return list;
}
}