有时候我们会遇到这种情况,通过两个不同的接口获取了两个user对象,在这个user里有很多字段,例如username、地址,生日、电话。user1里有username和地址,其他字段为空。user2里有生日、地址、电话,其他为空。想要合并两个user,可以使用if(user1.getXXX != null){user2.setXXX(user1.getXXX);}。正常情况下没问题。当user含有100个字段的时候,1000个字段的时候。这种方法就只有呵呵了。
先贴user的代码
public class user {
private String username;
private String address;
private String phone;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
下面是核心的合并算法
import java.lang.reflect.Method;
/**
* 使用Apache BeanUtil利用反射复制javabean
* 合并javabean用的
* @author 赵仁杰
*
*/
public class getandset{
/**
* 使用Apache BeanUtil利用反射复制javabean
* 如果obj1的某个get方法得出的参数不为空,则调用obj2的set方法,最后返回合并后的javabean
* @param obj1
* @param obj2
* @return obj2
* @throws Exception
*/
public static Object CopyBeanToBean(Object obj1, Object obj2)
throws Exception {
Method[] method1 = obj1.getClass().getMethods();
Method[] method2 = obj2.getClass().getMethods();
String methodName1;
String methodFix1;
String methodName2;
String methodFix2;
for (int i = 0; i < method1.length; i++) {
methodName1 = method1[i].getName();
methodFix1 = methodName1.substring(3, methodName1.length());
if (methodName1.startsWith("get")) {
for (int j = 0; j < method2.length; j++) {
methodName2 = method2[j].getName();
methodFix2 = methodName2.substring(3, methodName2.length());
if (methodName2.startsWith("set")) {
if (methodFix2.equals(methodFix1)) {
Object[] objs1 = new Object[0];
Object[] objs2 = new Object[1];
objs2[0] = method1[i].invoke(obj1, objs1);// 调用obj1的相应的get的方法,objs1数组存放调用该方法的参数,此例中没有参数,该数组的长度�?
if (objs2[0] != null && (!"".equals(objs2[0]))) {
method2[j].invoke(obj2, objs2);// 调用obj2的相应的set的方法,objs2数组存放调用该方法的参数
}
continue;
}
}
}
}
}
return obj2;
}
}
项目格式为utf-8
最后是测试类
public class test {
public static void main(String [] args) throws Exception{
user u1 = new user();
user u2 = new user();
u1.setAddress("中国");
u1.setAge(23);
u2.setPhone("11111111111");
u2.setUsername("赵仁杰");
u1 = (user) getandset.CopyBeanToBean(u1, u2);
System.out.println(u1.getAddress());
System.out.println(u1.getAge());
System.out.println(u1.getPhone());
System.out.println(u1.getUsername());
}
}
输出结果:
中国
23
11111111111
赵仁杰