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

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

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

//得到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方法),以及通过串行化将其返回到远程的客户机的时间总和。所以要小心使用这种威力!

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

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

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

3、实现这个转换类

BeanUtilsEx代码如下:

 

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);   
  
   }   
}  
 
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.. 上代码

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;   
             }   
         }   
           
     }   
  
}  
 
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

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();   
         }   
     }   
}  
 
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值