`
nesta2001zhang
  • 浏览: 69306 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用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)即可...

分享到:
评论

相关推荐

    反编译过的commons-beanutils.jar,时间值为空的情况下不会报错。

    开发得时候时间值为空,使用commons-beanutils.jar包的时候经常会报错,这个是我反编译的包,在时间值为空的情况下不会报错。

    使用servlet实现注册&登录&解决注册乱码&beanutils;的使用

    使用servlet实现注册&登录&解决注册乱码&beanutils;的使用

    BeanUtils用法

    其中,后三个子包主要用于数据的转换,围绕着一个Converter接口,该接口只有一个方法:java.lang.Object convert(java.lang.Class type, java.lang.Object value),用于将一个value转换成另一个类型为type的Object。...

    commons-beanutils-1.9.3

    BeanUtils工具由Apache软件基金组织编写,提供给我们使用,主要解决的问题是:把对象的属性数据封装到对象中。在整个J2EE的编程过程中,我们经常会从各种配置文件中读取相应的数据,需要明白的一点是从配置文件中...

    commons-beanutils-jesse.zip(20080825更新)

    增加了BeanUtils的copyProperty以及copyProperties方法对Date的null值复制功能,取消了当Date为null时的抛异常。 2008-08-25更新: 修改了Date转换为String的时候只能转换为短日期格式的问题,现在默认情况下都修改...

    beanutils-1.9.3-bin

    BeanUtils是由Apache公司开发的针对操作JavaBean的工具包。...但是由Apache公司开发的BeanUtils会更常用,同时,BeanUtils还需要配合第三方日志工具来使用,这里我们同样使用Apache公司的common logging

    beanutils使用

    beanutils使用的一个小例子,主要完成一个map转化成一个bean的过程

    BeanUtils_beanutils_

    BeanUtils 是 Apache commons组件的成员之一,主要用于简化JavaBean封装数据的操作。它可以给JavaBean封装一个字符串数据,也可以将一个表单提交的所有数据封装到JavaBean中。使用第三方工具,需要导入jar包:

    commons-beanutils使用工具包

    commons-beanutils使用工具包

    beanutils中文API.doc

    beanutil中包含大量和JavaBean操作有关的工具方法,使用beanutils可轻松利用Java反射机制来完成所需功能,而不需要详细研究反射的原理和使用,同时beanutils类库中提出了动态Bean的概念,可在运行时动态对Bean中属性...

    commons-beanutils-jesse.zip(20080717更新)

    2008-07-17更新: 增加了BeanUtils的copyProperty以及copyProperties方法对Date的null值复制功能,取消了当Date为null时的抛异常。 详情:...

    commons-beanutils-1.7.0.jar-解决commons-beanutils和commons-collections重复类

    解决办法是把commons-beanutils中的org/apache/commons/collections删除,这里上传一个改好可以直接使用的。

    BeanUtils工具

    BeanUtils工具是一种方便我们对JavaBean进行操作的工具,是Apache组织下的产品。beanUtils 可以便于对javaBean的属性、对象进行赋值,beanUtils可以将一个MAP集合的数据拷贝到一个javabean对象中。

    commons-beanutils-1.9.4-API文档-中文版.zip

    赠送jar包:commons-beanutils-1.9.4.jar; 赠送原API文档:commons-beanutils-1.9.4-javadoc.jar; 赠送源代码:commons-beanutils-1.9.4-sources.jar; 赠送Maven依赖信息文件:commons-beanutils-1.9.4.pom; ...

    BeanUtils_1.8.3帮助文档

    BeanUtils_1.8.3最新帮助文档,希望对给位有用。。。

    BeanUtils教程

    BeanUtils教程BeanUtils教程BeanUtils教程BeanUtils教程BeanUtils教程BeanUtils教程

    commons-beanutils-1.9.4-API文档-中英对照版.zip

    赠送jar包:commons-beanutils-1.9.4.jar; 赠送原API文档:commons-beanutils-1.9.4-javadoc.jar; 赠送源代码:commons-beanutils-1.9.4-sources.jar; 赠送Maven依赖信息文件:commons-beanutils-1.9.4.pom; ...

    commons-beanutils-1.9.CHM

    beanutil中包括大量和JavaBean操作有关的工具方法,使用它能够轻松利用Java反射机制来完毕代码中所须要的功能,而不须要具体研究反射的原理和使用,同一时候,该类库中提出了动态Bean的概念,不但提供现有JavaBean的...

    BeanUtils包

    BeanUtils工具由Apache软件基金组织编写,提供给我们使用,主要解决的问题是:把对象的属性数据封装到对象中

    commons-beanutils-jesse.zip

    apache的BeanUtils的copyProperty以及copyProperties方法不支持String与java.util.Date的类型相互转换 该包对源码进行了部分修改,使其支持对String与Date之间的类型转换. 注:该包在对null的Date转换时会抛出No value...

Global site tag (gtag.js) - Google Analytics