import java.lang.reflect.*;
/**
@author Xiaobo Zheng
@date 2005-12-28
*/
public class BeanUtil2{
/**
@parameter Object obj1,Object obj2
@return Object
用到反射機制
此方法將調用obj1的getter方法,將得到的值作為相應的參數傳給obj2的setter方法
注意,obj1的getter方法和obj2方法必須是public類型
*/
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 methodName1=method1[i].getName();
methodFix1=methodName1.substring(3,methodName1.length());
if(methodName1.startsWith("get")){
for(int j=0;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數組存放調用該方法的參數,此例中沒有參數,該數組的長度為0
method2[j].invoke(obj2,objs2);//激活obj2的相應的set的方法,objs2數組存放調用該方法的參數
continue;
}
}
}
}
}
return obj2;
}
}
再建一個javabean,并測試
import java.lang.reflect.*;
public class User {
private String name;
private String id;
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setId(String id){
this.id=id;
}
public String getId(){
return this.id;
}
public static void main(String[] args) throws Exception{
User u1=new User();
u1.setName("zxb");
u1.setId("3286");
User u2=new User();
u2=(User)BeanUtil2.CopyBeanToBean(u1,u2);
System.out.println(u2.getName());
System.out.println(u2.getId());
}
}
編譯后并執行輸出結果
zxb
3286
成功!
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/