【转】关于BeanUtils.copyProperties的用法和优缺点

一、简介: 
  BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。我们知道,一个JavaBean通常包含了大量的属性,很多情况下,对JavaBean的处理导致大量get/set代码堆积,增加了代码长度和阅读代码的难度。

二、用法: 
  BeanUtils是这个包里比较常用的一个工具类,这里只介绍它的copyProperties()方法。该方法定义如下: 

Java代码 
public static void copyProperties(java.lang.Object dest,java.lang.Object orig)   
    throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException 

  如果你有两个具有很多相同属性的JavaBean,一个很常见的情况就是Struts里的PO对象(持久对象)和对应的ActionForm,例如 Teacher和TeacherForm。我们一般会在Action里从ActionForm构造一个PO对象,传统的方式是使用类似下面的语句对属性逐个赋值:

复制代码

//得到TeacherForm   
TeacherForm teacherForm=(TeacherForm)form;   
  
//构造Teacher对象   
Teacher teacher=new Teacher();   
  
//赋值   
teacher.setName(teacherForm.getName());   
teacher.setAge(teacherForm.getAge());   
teacher.setGender(teacherForm.getGender());   
teacher.setMajor(teacherForm.getMajor());   
teacher.setDepartment(teacherForm.getDepartment());   
  
//持久化Teacher对象到数据库   
HibernateDAO.save(teacher);     

复制代码

而使用BeanUtils后,代码就大大改观了,如下所示:   

复制代码

//得到TeacherForm   
TeacherForm teacherForm=(TeacherForm)form;   
  
//构造Teacher对象   
Teacher teacher=new Teacher();   
  
//赋值   
BeanUtils.copyProperties(teacher,teacherForm);   
  
//持久化Teacher对象到数据库   
HibernateDAO.save(teacher);  

复制代码

  如果Teacher和TeacherForm间存在名称不相同的属性,则BeanUtils不对这些属性进行处理,需要程序员手动处理。例如 Teacher包含modifyDate(该属性记录最后修改日期,不需要用户在界面中输入)属性而TeacherForm无此属性,那么在上面代码的 copyProperties()后还要加上一句:

teacher.setModifyDate(new Date());  

  怎么样,很方便吧!除BeanUtils外还有一个名为PropertyUtils的工具类,它也提供copyProperties()方法,作用与 BeanUtils的同名方法十分相似,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,而前者不支持这个功能,但是速度会更快一些。BeanUtils支持的转换类型如下:

复制代码

* java.lang.BigDecimal   
  
* java.lang.BigInteger   
  
* boolean and java.lang.Boolean   
  
* byte and java.lang.Byte   
  
* char and java.lang.Character   
  
* java.lang.Class   
  
* double and java.lang.Double   
  
* float and java.lang.Float   
  
* int and java.lang.Integer   
  
* long and java.lang.Long   
  
* short and java.lang.Short   
  
* java.lang.String   
  
* java.sql.Date   
  
* java.sql.Time   
  
* java.sql.Timestamp  

复制代码

  这里要注意一点,java.util.Date是不被支持的,而它的子类java.sql.Date是被支持的。因此如果对象包含时间类型的属性,且希望被转换的时候,一定要使用java.sql.Date类型。否则在转换时会提示argument mistype异常。

三、优缺点: 
  Apache Jakarta Commons项目非常有用。我曾在许多不同的项目上或直接或间接地使用各种流行的commons组件。其中的一个强大的组件就是BeanUtils。我 将说明如何使用BeanUtils将local实体bean转换为对应的value 对象:
BeanUtils.copyProperties(aValue, aLocal)  

  上面的代码从aLocal对象复制属性到aValue对象。它相当简单!它不管local(或对应的value)对象有多少个属性,只管进行复制。我们假设 local对象有100个属性。上面的代码使我们可以无需键入至少100行的冗长、容易出错和反复的get和set方法调用。这太棒了!太强大了!太有用 了! 
  现在,还有一个坏消息:使用BeanUtils的成本惊人地昂贵!我做了一个简单的测试,BeanUtils所花费的时间要超过取数 据、将其复制到对应的 value对象(通过手动调用get和set方法),以及通过串行化将其返回到远程的客户机的时间总和。所以要小心使用这种威力!

展开阅读全文

BeanUtils.copyProperties() 异常问题

03-18

CharacterEncodingFilter -> public void doFilterrnSupperAction -> public ActionForward executernCategoryAction -> public ActionForward editrn1====cf.getId: 1rnCategoryDao->public Category loadCategory(int id)rn*****rn*****rnc====1rnHibernate: select category0_.id as id1_0_, category0_.name as name1_0_, category0_.description as descript3_1_0_, category0_.createTime as createTime1_0_ from tb_category category0_ where category0_.id=?rn21:35:01,353 ERROR DispatchAction:293 - Dispatch[/baseData/category] to method 'edit' returned an exceptionrnjava.lang.reflect.InvocationTargetExceptionrn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)rn at com.gnsas.struts.action.SupperAction.execute(SupperAction.java:43)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at com.gnsas.util.HibernateFilter.doFilter(HibernateFilter.java:50)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at com.gnsas.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)rn at java.lang.Thread.run(Thread.java:662)rnCaused by: java.lang.NoClassDefFoundError: com/sun/org/apache/commons/beanutils/BeanUtilsrn at com.gnsas.struts.action.CategoryAction.edit(CategoryAction.java:73)rn ... 31 morernCaused by: java.lang.ClassNotFoundException: com.sun.org.apache.commons.beanutils.BeanUtilsrn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)rn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)rn ... 32 morern21:35:01,371 WARN RequestProcessor:528 - Unhandled Exception thrown: class javax.servlet.ServletExceptionrn2011-3-18 21:35:01 org.apache.catalina.core.StandardWrapperValve invokern严重: Servlet.service() for servlet action threw exceptionrnjava.lang.ClassNotFoundException: com.sun.org.apache.commons.beanutils.BeanUtilsrn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)rn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)rn at com.gnsas.struts.action.CategoryAction.edit(CategoryAction.java:73)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)rn at com.gnsas.struts.action.SupperAction.execute(SupperAction.java:43)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at com.gnsas.util.HibernateFilter.doFilter(HibernateFilter.java:50)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at com.gnsas.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)rn at java.lang.Thread.run(Thread.java:662)rnrnrnrnrn//编辑类别rn public ActionForward edit(ActionMapping mapping, ActionForm form,rn HttpServletRequest request, HttpServletResponse response)rn throws Exception rn System.out.println("CategoryAction -> public ActionForward edit");rn CategoryForm cf = (CategoryForm)form;rn // 判断id是否有效rn if(cf.getId() > 0)rn CategoryDao dao = new CategoryDao();rn System.out.println("1====cf.getId: "+cf.getId());rn Category cat = dao.loadCategory(cf.getId());rn System.out.println("c===="+cat.getId());rnrn[b] BeanUtils.copyProperties(cf, cat); [/b]rn rn System.out.println("copy===="+cf.getId());rn rn rn return mapping.findForward("edit");rn 问答

没有更多推荐了,返回首页