将源对象number类型属性的值,赋值给目标对象同类型的属性
当目标对象属性为0时 在源对象中寻找 同属性但值不为0 的属性 ,然后赋值给目标对象
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class BeanUtils {
public static void copyProperties(Object target, Object... sources) {
Field[] fields = target.getClass().getDeclaredFields();
String[] fieldNamStrings = new String[fields.length];
for (int i = 0; i < fieldNamStrings.length; i++) {
fieldNamStrings[i] = fields[i].getName();
}
for (String fieldName : fieldNamStrings) {
try {
Object getMethod = getGetMethod(target, fieldName);
if (getMethod instanceof Double && (double) getMethod == 0.0D) {
setValue(target, fieldName, sources);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 根据属性,获取get方法
*
* @param ob 对象
* @param name 属性名
* @return 属性值
* @throws Exception
*/
private static Object getGetMethod(Object ob, String name) throws Exception {
Method[] m = ob.getClass().getMethods();
for (Method method : m) {
if (("get" + name).toLowerCase().equals(method.getName().toLowerCase())) {
return method.invoke(ob);
}
}
return null;
}
/**
* 根据属性,拿到set方法,并把值set到对象中
*/
private static void setValue(Object target, String fieldName, Object... sources) {
try {
for (Object source : sources) {
Object data = getGetMethod(source, fieldName);
if (data != null && (double) data != 0) {
String setMethodName = "set" + fieldName;
Method[] methods = target.getClass().getMethods();
for (Method method : methods) {
if (setMethodName.equals(method.getName().toLowerCase())) {
method.invoke(target,data);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}