public class BeanUtils {
private static final String DEFAULT_HYPHEN = "-";
public static void copyProperties(Object source, Object target) {
org.springframework.beans.BeanUtils.copyProperties(source, target);
try {
copyPropertiesExtension(source, target);
} catch (Exception e) {
log.error("反射调用/访问方法异常", e);
throw new RuntimeException(e);
}
}
public static void copyPropertiesExtension(Object source, Object target) throws InvocationTargetException, IllegalAccessException {
Class<?> sourceClazz = source.getClass();
Field[] sourceFields = sourceClazz.getDeclaredFields();
Class<?> targetClazz = target.getClass();
Field[] targetFields = targetClazz.getDeclaredFields();
HashMap<String, Field> targetFieldsMap = Maps.newHashMap();
for (Field targetField : targetFields) {
targetFieldsMap.put(targetField.getName(), targetField);
}
for (Field sourceField : sourceFields) {
String sourceFieldName = sourceField.getName();
Field targetField = targetFieldsMap.get(sourceFieldName);
if (targetField != null && "class java.lang.String".equals(targetField.getType().toString())) {
targetField.setAccessible(true);
Method sourceMethod;
try {
sourceMethod = source.getClass().getMethod("get" + getMethodName(sourceFieldName));
} catch (NoSuchMethodException e) {
log.error("找不到方法", e);
throw new RuntimeException(e);
}
String fieldType = sourceField.getType().toString();
if ("class java.lang.Double".equals(fieldType)) {
Double invoke = (Double) sourceMethod.invoke(source);
if (invoke != null) {
targetField.set(target, invoke.toString());
}
} else if ("class java.lang.Integer".equals(fieldType)) {
Integer invoke = (Integer) sourceMethod.invoke(source);
if (invoke != null) {
targetField.set(target, invoke.toString());
}
} else if ("class java.lang.Long".equals(fieldType)) {
Long invoke = (Long) sourceMethod.invoke(source);
if (invoke != null) {
targetField.set(target, invoke.toString());
}
}
}
}
}
private static String getMethodName(String str) {
byte[] items = str.getBytes();
items[0] = (byte) ((char) items[0] - 'a' + 'A');
return new String(items);
}
public static void convertNullFieldValue(Object obj) {
convertNullFieldValue(obj, DEFAULT_HYPHEN);
}
public static void convertNullFieldValue(Object obj, String str) {
Class<?> clazz = obj.getClass();
Field[] declaredFields = clazz.getDeclaredFields();
if (declaredFields.length == 0) {
return;
}
for (Field field : declaredFields) {
field.setAccessible(true);
try {
if (field.get(obj) == null && "class java.lang.String".equals(field.getType().toString())) {
field.set(obj, str);
}
} catch (IllegalAccessException e) {
throw new RuntimeException();
}
}
}
}