使用BeanUtils时,Date类型值为空的解决方法

来源:互联网 发布:DRGS网络上报 编辑:程序博客网 时间:2024/04/28 01:11

org.apache.commons.beanutils.ConversionException: No value specified for 'Date'
现在系统里原先不出错的地方老是出现以上这个错误,不知道什么原因。也都是BeanUtils.copyProperties(teaInfo, infoForm);这种语句出的错。

今天查了一上午,找到了它的用法,原来它是一种反射机制,使用copyProperties可以复制bean,不必重复写很多属性,只是效率不高。

1, BeanUtils.copyProperties(dest, orig);          这种copy是浅拷贝,复制后的2个Bean的同一个属性可能拥有同一个对象的ref,这个在使用时要小心,特别是对于属性为自定义类的情况.还要属性为集合类的情况。小心hibernate的Set
2,BeanUtils.copyProperties与PropertyUtils.copyProperties的区别
这两个类几乎有一摸一样的功能,唯一的区别是:BeanUtils在对Bean赋值是会进行类型转化。举例来说也就是在copyProperty时只要属性名相同,就算类型不同,BeanUtils也可以进行copy;而PropertyBean则可能会报错。当然2个Bean之间的同名属性的类型必须是可以转化的,否则用BeanUtils一样会报错。          若实现了org.apache.commons.beanutils.Converter接口则可以自定义类型之间的转化。
除BeanUtils外还有一个名为PropertyUtils的工具类,它也提供copyProperties()方法,作用与BeanUtils的同名方法十分相似,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,而前者不支持这个功能,但是速度会更快一些
http://xiaozhao-521.javaeye.com/blog/244254
注意:有人说BeanUtils支持的转换类型不包括java.util.Date?
     我用1.6.1版本试了BeanUtils.copyProperties,肯定是支持java.util.Date的。
3,LazyDynaBean可以实现动态的vo。
这样,有时候程序给view层的东西就可以用它来封装而不用专门建一个多余的vo类了。
参考:
http://jone0321.blogdriver.com/jone0321/615543.html
http://www.blogjava.net/kenzhh/archive/2008/09/03/226592.html

BeanUtils.copyProperties与PropertyUtils.copyProperties用法及区别

一、简介:
BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。我们知道,一个JavaBean通常包含了大量的属性,很多情况下,对JavaBean的处理导致大量get/set代码堆积,增加了代码长度和阅读代码的难度。
二、用法:
BeanUtils是这个包里比较常用的一个工具类,这里只介绍它的copyProperties()方法。该方法定义如下:

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对象,传统的方式是使用类似下面的语句对属性逐个赋值:

//得到TeacherFormTeacherForm 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后,代码就大大改观了,如下所示://得到TeacherFormTeacherForm 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方法),以及通过串行化将其返回到远程的客户机的时间总和。所以要小心使用这种威力!

使用BeaUtils.copyProperties时,如果源目标中包含Date类型(sql.date,util,date)字段,而且该字段值为空时,会出现异常,无法赋值,解决方法如下:

1、建立一个新的BeaUtilsEx类继承BeanUtils

2、在其中声名Date类型的转换类

3、实现这个转换类

BeanUtilsEx代码如下:

Java代码

  1. package com.fish.util;   
  2. import org.apache.commons.beanutils.ConvertUtils;   
  3. import org.apache.commons.beanutils.BeanUtils;   
  4. import org.apache.commons.logging.Log;   
  5. import org.apache.commons.logging.LogFactory;   
  6. import java.util.HashMap;   
  7. import java.util.Map;   
  8. import java.lang.reflect.*;   
  9. public final class BeanUtilEx   
  10. extends BeanUtils {   
  11. private static Map cache = new HashMap();   
  12. private static Log logger = LogFactory.getFactory().getInstance(BeanUtilEx.class);   
  13. private BeanUtilEx() {   
  14.    }   
  15. static {   
  16. //注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
  17. ConvertUtils.register(new SqlDateConverter(), java.util.Date.class);
  18. //ConvertUtils.register(new SqlTimestampConverter(), java.sql.Timestamp.class);
  19. //注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
  20.      ConvertUtils.register(new UtilDateConverter(), java.util.Date.class);
  21.    }   
  22. public static void copyProperties(Object target, Object source) throws
  23.        InvocationTargetException, IllegalAccessException {   
  24. //update bu zhuzf at 2004-9-29
  25. //支持对日期copy
  26.      org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);   
  27.    }   
  28. }  
package com.fish.util;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import java.util.HashMap;import java.util.Map;import java.lang.reflect.*;public final class BeanUtilEx    extends BeanUtils {  private static Map cache = new HashMap();  private static Log logger = LogFactory.getFactory().getInstance(BeanUtilEx.class);  private BeanUtilEx() {  }  static {    //注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空    ConvertUtils.register(new SqlDateConverter(), java.util.Date.class);    //ConvertUtils.register(new SqlTimestampConverter(), java.sql.Timestamp.class);    //注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空    ConvertUtils.register(new UtilDateConverter(), java.util.Date.class);  }  public static void copyProperties(Object target, Object source) throws      InvocationTargetException, IllegalAccessException {    //update bu zhuzf at 2004-9-29    //支持对日期copy    org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);  }}

至于转换类SqlDateConverter和UtilDateConverter,实现起来很简单,这里省略

改进BeanUtils支持DATE类型

项目中经常要用到BeanUtils, 可惜的是BeanUtils只支持基本数据类型转换, 最麻烦的是连比较常用的DATE类型都不支持, 无奈之下只好改装..

实际上只需要扩展Converter, 增加一个Converter接口的实例DateConvert, 在内部写好转换方法并注册就OK.. 上代码

Java代码 复制代码

  1. import java.text.ParseException;   
  2. import java.text.SimpleDateFormat;   
  3. import org.apache.commons.beanutils.Converter;   
  4. /**
  5. *
  6. * @author lucas
  7. */
  8. public class DateConvert implements Converter {   
  9. public Object convert(Class arg0, Object arg1) {   
  10.          String p = (String)arg1;   
  11. if(p== null || p.trim().length()==0){   
  12. return null;   
  13.          }      
  14. try{   
  15.              SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
  16. return df.parse(p.trim());   
  17.          }   
  18. catch(Exception e){   
  19. try {   
  20.                  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");   
  21. return df.parse(p.trim());   
  22.              } catch (ParseException ex) {   
  23. return null;   
  24.              }   
  25.          }   
  26.      }   
  27. }  
import java.text.ParseException;import java.text.SimpleDateFormat;import org.apache.commons.beanutils.Converter;/** * * @author lucas */public class DateConvert implements Converter {    public Object convert(Class arg0, Object arg1) {        String p = (String)arg1;        if(p== null || p.trim().length()==0){            return null;        }           try{            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            return df.parse(p.trim());        }        catch(Exception e){            try {                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");                return df.parse(p.trim());            } catch (ParseException ex) {                return null;            }        }            }}

然后再写一个BeanUtilsEx继承BeanUtils, 并在里面注册DateConvert

Java代码 复制代码

  1. import java.lang.reflect.InvocationTargetException;   
  2. import org.apache.commons.beanutils.BeanUtils;   
  3. import org.apache.commons.beanutils.ConvertUtils;   
  4. /**
  5. *
  6. * @author lucas
  7. */
  8. public class BeanUtilsEx extends BeanUtils {   
  9. static {   
  10.          ConvertUtils.register(new DateConvert(), java.util.Date.class);   
  11.          ConvertUtils.register(new DateConvert(), java.sql.Date.class);   
  12.      }   
  13. public static void copyProperties(Object dest, Object orig) {   
  14. try {   
  15.              BeanUtils.copyProperties(dest, orig);   
  16.          } catch (IllegalAccessException ex) {   
  17.              ex.printStackTrace();   
  18.          } catch (InvocationTargetException ex) {   
  19.              ex.printStackTrace();   
  20.          }   
  21.      }   
  22. }  
import java.lang.reflect.InvocationTargetException;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;/** * * @author lucas */public class BeanUtilsEx extends BeanUtils {    static {        ConvertUtils.register(new DateConvert(), java.util.Date.class);        ConvertUtils.register(new DateConvert(), java.sql.Date.class);    }    public static void copyProperties(Object dest, Object orig) {        try {            BeanUtils.copyProperties(dest, orig);        } catch (IllegalAccessException ex) {            ex.printStackTrace();        } catch (InvocationTargetException ex) {            ex.printStackTrace();        }    }}


BeanUtilsEx.copyProperties(dest, orig)即可...

0 0
原创粉丝点击