importjava.lang.reflect.*;
/**
@authorXiaoboZheng
@date2005-12-28
*/
publicclassBeanUtil2{
/**
@parameterObjectobj1,Objectobj2
@returnObject
用到反射机制
此方法将调用obj1的getter方法,将得到的值作为相应的参数传给obj2的setter方法
注重,obj1的getter方法和obj2方法必须是public类型
*/
publicstaticObjectCopyBeanToBean(Objectobj1,Objectobj2)throwsException{
Method[]method1=obj1.getClass().getMethods();
Method[]method2=obj2.getClass().getMethods();
StringmethodName1;
StringmethodFix1;
StringmethodName2;
StringmethodFix2;
for(inti=0;i
methodFix1=methodName1.substring(3,methodName1.length());
if(methodName1.startsWith("get")){
for(intj=0;j
methodFix2=methodName2.substring(3,methodName2.length());
if(methodName2.startsWith("set")){
if(methodFix2.equals(methodFix1)){
Object[]objs1=newObject[0];
Object[]objs2=newObject[1];
objs2[0]=method1[i].invoke(obj1,objs1);//激活obj1的相应的get的方法,objs1数组存放调用该方法的参数,此例中没有参数,该数组的长度为0
method2[j].invoke(obj2,objs2);//激活obj2的相应的set的方法,objs2数组存放调用该方法的参数
continue;
}
}
}
}
}
returnobj2;
}
}
再建一个javabean,并测试
importjava.lang.reflect.*;
publicclassUser{
privateStringname;
privateStringid;
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetName(){
returnthis.name;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetId(){
returnthis.id;
}
publicstaticvoidmain(String[]args)throwsException{
Useru1=newUser();
u1.setName("zxb");
u1.setId("3286");
Useru2=newUser();
u2=(User)BeanUtil2.CopyBeanToBean(u1,u2);
System.out.println(u2.getName());
System.out.println(u2.getId());
}
}
编译后并执行输出结果
zxb
3286
成功!
