java - BeanUtils 日期转换问题

标签 java type-conversion

我尝试使用 BeanUtils 将数据(java.util.Date)值从源复制到目标。它给出了日期到字符串转换异常。

此类问题的解决方案是什么?

我的实现如下..

 import java.util.Date;

 public class Bean1 {

 private Date date;

 public Bean1() {

   }

 public Date getDate() {
   return date;
   }

 public void setDate(Date date) {
   this.date = date;
   }

}

================================================== ===========

import java.util.Date;

public class Bean2 {

private Date date;

public Bean2() {

}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

}

================================================== ===========

我的复制属性方法如下

    public static void copyProperties(Object src, Object dest) throws   llegalAccessException,InvocationTargetException, NoSuchMethodException {
         Field[] attributes = dest.getClass().getDeclaredFields();
         for (Field property : attributes) {              
           BeanUtils.setProperty(dest, property.getName(), BeanUtils.getProperty(
                src, property.getName()));
    }
}

最佳答案

最新版本的 BeanUtils 不支持直接复制 Date 属性。您需要实现一个转换器(也是 benutils 包的一部分)并将该转换器与您的复制属性方法一起使用。这是为了避免导致两个对象中日期属性格式存在差异的任何错误。像下面这样的东西适合你

    public static void copyProperties(Object arg0, Object arg1) 
            throws IllegalAccessException, InvocationTargetException {
        java.util.Date defaultValue = null;
        Converter converter = new DateConverter(defaultValue);
        BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance(); 
        beanUtilsBean.getConvertUtils().register(converter, java.util.Date.class);
        beanUtilsBean.copyProperties(arg0, arg1);
    }

如果您确定两个对象中的日期格式保持相同,我建议您使用 PropertyUtils。仅当源和目标上的日期属性的日期格式可能不同时,才需要使用转换器。

关于java - BeanUtils 日期转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561292/

相关文章:

java - ./gradlew 因 NoSuchAlgorithmException 失败

java - 如何正确使用 GridLayout 在 JFrame 中定位元素?

java - 将参数传递给来自 xml 的不同切入点的相同切面方法

java - 类型不匹配 : cannot convert from integer to boolean

java - 通过 JNI 读取文件时崩溃,但仅运行代码的 C 元素时成功

java - 提示用户输入 N*N 数组的每一行

c++ - CGAL 中精确数字的序列化

type-conversion - 无法将 LongType 转换为 DateType 错误

javascript - 在 JavaScript 中将 int64 值转换为 Number 对象

vb.net - CDbl在做什么?