在struts的实践过程中,经常两个javabean交换数据的情况,如actionform与数据库中的表相关的bean交换数据。通常情况下要写很多get和set语句,一个个属性依次拷贝。这样的话,如此重复繁重的工作让程序员感觉不到编程的快乐。于是在网上查相关资料知,在apache.org有一个project:common-beanutil,提供的一个beanutil类,这个类有一个静态方法beanutil.copyproperties()实现了该功能。后来我在与java相关的书上知道的java的反射机制(reflect),偿试着并实现了两个javabean的属性拷贝功能。
import java.lang.reflect.*;
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<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数组存放调用该方法的参数,
此例中没有参数,该数组的长度为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
成功!