javabean对象自动赋值给另一个javabean对象.doc
上传人:sy****28 上传时间:2024-09-14 格式:DOC 页数:3 大小:14KB 金币:16 举报 版权申诉
预览加载中,请您耐心等待几秒...

javabean对象自动赋值给另一个javabean对象.doc

javabean对象自动赋值给另一个javabean对象.doc

预览

在线预览结束,喜欢就下载吧,查找使用更方便

16 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

HYPERLINK"http://diaoge.iteye.com/blog/209906"javabean对象自动赋值给另一个javabean对象把JavaBean的from的值自动set给to,省略了自己从from中get然后再set给topublicstaticObjectconvertBean2Bean(Objectfrom,Objectto){try{BeanInfobeanInfo=Introspector.getBeanInfo(to.getClass());PropertyDescriptor[]ps=beanInfo.getPropertyDescriptors();for(PropertyDescriptorp:ps){MethodgetMethod=p.getReadMethod();MethodsetMethod=p.getWriteMethod();if(getMethod!=null&&setMethod!=null){try{Objectresult=getMethod.invoke(from);setMethod.invoke(to,result);}catch(Exceptione){//如果from没有此属性的get方法,跳过continue;}}}}catch(Exceptione){e.printStackTrace();}returnto;}/***不支持to继承(to是其他bean的子类)*/publicstaticObjectcoverBean2Bean(Objectfrom,Objectto){ClassfClass=from.getClass();ClasstClass=to.getClass();//拿to所有属性(如果有继承,父类属性拿不到)Field[]cFields=tClass.getDeclaredFields();try{for(Fieldfield:cFields){StringcKey=field.getName();//确定第一个字母大写cKey=cKey.substring(0,1).toUpperCase()+cKey.substring(1);MethodfMethod;ObjectfValue;try{fMethod=fClass.getMethod("get"+cKey);//public方法fValue=fMethod.invoke(from);//取getfKey的值}catch(Exceptione){//如果from没有此属性的get方法,跳过continue;}try{//用fMethod.getReturnType(),而不用fValue.getClass()//为了保证get方法时,参数类型是基本类型而传入对象时会找不到方法MethodcMethod=tClass.getMethod("set"+cKey,fMethod.getReturnType());cMethod.invoke(to,fValue);}catch(Exceptione){//如果to没有此属性set方法,跳过continue;}}}catch(Exceptione){e.printStackTrace();}returnto;}staticfinalStringspare="======================================================\r\n";/***打印bean信息*/publicstaticvoidprintInvoke(Objectobject){Method[]ms=object.getClass().getMethods();Stringstr=spare;str+="startlogobject:"+object.getClass().getSimpleName()+"\r\n";str+=spare;System.out.print(str);for(inti=0;i<ms.length;i++){if(ms[i].getName().indexOf("get")!=-1&&!ms[i].getName().equals("getClass")){try{System.out.println(ms[i].getName()+"="+ms[i].invoke(object));}catch(Exceptione){e.printStackTrace();}}}System.out.println(spare);