BeanUtils.copyProperties扩展--实现String转Date

BeanUtils.copyProperties(target,source)和PropertyUtils.copyProperties(target,source)都能将源对象的属性的值拷贝到目标对象相同属性名中。

区别在于:

BeanUtils.copyProperties(target,source)

支持基础类型、String、java.sql.Date、java.sql.Timestamp、java.sql.Time之间的类型转换,即只要这些类型的属性名相同那么拷贝就能成功。但是会默认初始化属性值。注意:不支持java.util.Date类型的转化,需手动设置。

PropertyUtils.copyProperties(target,source)

不支持类型转换,但是不会初始话属性值,允许属性值为null。

在webservice中遇到了一个String类型,但是数据库是java.util.Date类型,因为对象属性不较多,所以在使用PropertyUtils.copyProperties(target,source)时报错。

后来查了下资料,说BeanUtils能进行类型转换,故而就自定义了一个String转Date的工具类。

定义工具类

package com.dhcc.phms.common.beanutils;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class BeanUtilsEx extends BeanUtils{

  static {
      //注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
      ConvertUtils.register(new DateConvert(), java.util.Date.class);
      ConvertUtils.register(new DateConvert(), String.class);
//      BeanUtilsBean beanUtils = new BeanUtilsBean(ConvertUtils.class,new PropertyUtilsBean());
 }

 public static void copyProperties(Object target, Object source) throws
        InvocationTargetException, IllegalAccessException {
      //支持对日期copy

   org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
 }
}

定义日期转换格式

package com.dhcc.phms.common.beanutils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
public class DateConvert implements Converter{

 @Override
 public Object convert(Class class1, Object value) {
  if(value == null){
   return null;
  }
  if(value instanceof Date){
   return value;
  }
  if (value instanceof Long) {
   Long longValue = (Long) value;
   return new Date(longValue.longValue());
  }
  if (value instanceof String) {
   String dateStr = (String)value;
   Date endTime = null;
   try {
    String regexp1 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
    String regexp2 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9]) ([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
    String regexp3 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])";
    if(dateStr.matches(regexp1)){
     dateStr = dateStr.split("T")[0]+" "+dateStr.split("T")[1];
     DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     endTime = sdf.parse(dateStr);
     return endTime;
    }else if(dateStr.matches(regexp2)){
     DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     endTime = sdf.parse(dateStr);
     return endTime;
    }else if(dateStr.matches(regexp3)){
     DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     endTime = sdf.parse(dateStr);
     return endTime;
    }else{
     return dateStr;
    }
   } catch (ParseException e) {
    e.printStackTrace();
   }
  }
  return value;
 }
}

使用时用BeanUtilsEx. copyProperties(target,source)时即可实现String转换为Date。

除此之外,如果需要转换的属性比较少时,可先将source对象中冲突属性取出来,另存一份,然后将该属性值置为null,因为不会拷贝null属性,所以拷贝的时候不会出错。当拷贝完成后再将冲突属性转换为所需格式,set进目标对象。这样也是实现效果。

测试代码如下:

目标对象TargetObject

package test;
import java.util.Date;
public class TargetObject {
 Date date;
 Boolean isOther;

 public TargetObject(Date date,Boolean isOther) {
  super();
  this.date = date;
  this.isOther = isOther;
 }

 public TargetObject() {
  super();
  // TODO Auto-generated constructor stub
 }

 public Date getDate() {
  return date;
 }

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

 public Boolean getIsOther() {
  return isOther;
 }

 public void setIsOther(Boolean isOther) {
  this.isOther = isOther;
 }

 @Override
 public String toString() {
  return "TargetObject [date=" + date + ", isOther=" + isOther + "]";
 }

}

源对象SourceObject

package test;
public class SourceObject {
 String date;
 String other;

 public SourceObject(String date,String other) {
  super();
  this.date = date;
  this.other = other;
 }

 public SourceObject() {
  super();
  // TODO Auto-generated constructor stub
 }

 public String getDate() {
  return date;
 }

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

 public String getOther() {
  return other;
 }

 public void setOther(String other) {
  this.other = other;
 }

 @Override
 public String toString() {
  return "SourceObject [date=" + date + ", other=" + other + "]";
 }
}

测试代码

public static void main(String[] args) {
     SourceObject source = new SourceObject("2017-07-17","false");
     TargetObject target = new TargetObject();
     try {
   BeanUtilsEx.copyProperties(target,source);
   System.out.println(source.toString());//SourceObject [date=2017-07-17, other=false]
   System.out.println(target.toString());//TargetObject [date=Mon Jul 17 00:00:00 CST 2017, isOther=null]
   if(source.getOther().equals("true")) {//对于属性名不一样的属性是不会赋值的,需要手动设置
    target.setIsOther(true);
   }else {
    target.setIsOther(false);
   }
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }

BeanUtils.copyProperties 日期转字符 日期转Long

建立自己的日期转换类

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.time.DateUtils;

public class DateConverter implements Converter {
 private static final SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 @Override
 public Object convert(Class type, Object value) {
  if(value == null) {
         return null;
     }
     if(value instanceof Date) {
         return value;
     }
     if(value instanceof Long) {
         Long longValue = (Long) value;
         return new Date(longValue.longValue());
     }
        try {
            return dateFormat.parse(value.toString());
            //return DateUtils.parseDate(value.toString(), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm" });
        } catch (Exception e) {
            throw new ConversionException(e);
        }
 }
}

使用自己的日期转换类替代默认的。如下面的main函数

public static void main(String[] args) {
                //替换
                ConvertUtils.register(new DateConverter(), Date.class);
  //ConvertUtils.register(new StringConverter(), String.class);
  A a = new A();
  a.date="2012-03-14 17:22:16";
  B b = new B();
  try {
   BeanUtils.copyProperties(b, a);
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(b.getDate());
 }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 解决BeanUtils.copyProperties无法成功封装的问题

    BeanUtils.copyProperties无法封装 使用 BeanUtils.copyProperties(user, memeber); 两个类中字段一样,但个别字段无法封装. 期初以为或许是字段的属性不同,仔细检查过还是一样,最后发现,是get.set方法名不同的原因. 如下 user里面有个字段为abc,他的get方法名为getABC(); member里面同样的字段abc,他的get方法名为getAbc(); 最后导致abc的字段无法成功封装 BeanUtils.copyPrope

  • 解决Beanutils.copyproperties实体类对象不一致的问题

    今天给大家分析一个解决Beanutils.copyproperties实体类对象名不一致的解决方法,一般我们在两个对象拷贝的问题上,我个人用的比较多的就是Beanutils.copyproperties,字段名如果不一致的话就去实体类中使用重载,把当前实体类的对象赋值给另外一个对象,也有用到set(),当然这些也都能解决Beanutils.copyproperties实体类属性不一致的问题,不过今天要给大家分享的是,不用set()和实体类的重构,使用类的反射机制去完成! 话不多说直接开始: 我是

  • BeanUtils.copyProperties在拷贝属性时忽略空值的操作

    BeanUtils.copyProperties忽略空值 使用spring开发的人,对这行代码肯定不陌生,常用于DTO.VO.PO之间的复制. /** * 全属性copy对象 * **/ BeanUtils.copyProperties(Object source, Object target) 但这行代码会将所有的属性都进行copy,有的时候我们想要个别属性不进行复制(比如:null值属性),这时就需要用到另一个方法: /** * 忽略某些属性copy对象 * **/ BeanUtils.co

  • 解决BeanUtils.copyProperties不支持复制集合的问题

    工作中,经常使用Spring的工具类BeanUtils.copyProperties对bean属性进行复制,这里的复制属于浅复制.且不能复制集合和数组.本文会对该工具进行一些测试. 文末会提出复制集合属性的解决方案 准备工作:准备测试需要的类 @Data public class Class { private People[] member; private People teacher; private List<People> student; } @Data @NoArgsConstr

  • 基于Spring BeanUtils的copyProperties方法使用及注意事项

    如下所示: package com.demo; import lombok.Data; import org.springframework.beans.BeanUtils; import java.util.Arrays; import java.util.List; /** * @author xiaobu * @version JDK1.8.0_171 * @date on 2019/10/8 10:04 * @description */ public class BeanUtilsTe

  • 如何使用BeanUtils.copyProperties进行对象之间的属性赋值

    1.使用org.springframework.beans.BeanUtils.copyProperties方法进行对象之间属性的赋值,避免通过get.set方法一个一个属性的赋值 /** * 对象属性拷贝 <br> * 将源对象的属性拷贝到目标对象 * * @param source 源对象 * @param target 目标对象 */ public static void copyProperties(Object source, Object target) { try { BeanU

  • 关于BeanUtils.copyProperties(source, target)的使用

    BeanUtils.copyProperties 首先,使用的是org.springframework.beans.BeanUtils; source 来源, target 目标 顾名思义, BeanUtils.copyProperties(source, target); 第一个参数是需要拷贝的目标,第二个参数是拷贝后的目标. 因为这个方法有很多种情况,容易分不清,所以今天测了一下不同情况下的结果如何. 1.target里面有source里没有的属性 并且此属性有值时 2.target和sou

  • java Beanutils.copyProperties( )用法详解

    这是一篇开发自辩甩锅稿~~~~ 昨天测试小姐姐将我的一个bug单重开了,emmmm....内心OS:就调整下对象某个属性类型这么简单的操作,我怎么可能会出错呢,一定不是我的锅!!but再怎么抗拒,bug还是要改的,毕竟晚上就要发版本了~~ 老老实实将我前天改的部分跟了一遍,恩,完美,没有任何的缺失~~but本应success的测试数据,接口返还的结果确实是false来着,那还是老老实实debug吧. 一步步跟下来,恩,多么顺畅,就说一定不是我的锅~~诶?不对不对,这里的ID值,为啥是null?传

  • java使用BeanUtils.copyProperties踩坑经历

    1. 原始转换 提起对象转换,每个程序员都不陌生,比如项目中经常涉及到的DO.DTO.VO之间的转换,举个例子,假设现在有个OrderDTO,定义如下所示: public class OrderDTO { private long id; private Long userId; private String orderNo; private Date gmtCreated; // 省略get.set方法 } 有个OrderVO,定义如下所示: public class OrderVO { pr

  • BeanUtils.copyProperties扩展--实现String转Date

    BeanUtils.copyProperties(target,source)和PropertyUtils.copyProperties(target,source)都能将源对象的属性的值拷贝到目标对象相同属性名中. 区别在于: BeanUtils.copyProperties(target,source) 支持基础类型.String.java.sql.Date.java.sql.Timestamp.java.sql.Time之间的类型转换,即只要这些类型的属性名相同那么拷贝就能成功.但是会默认

  • BeanUtils.copyProperties复制不生效的解决

    目录 前言 问题的排查 问题的扩展 前言 呵呵 前端时间使用 BeanUtils.copyProperties 的时候碰到了一个这样的问题 我有两个实体, 有同样的属性, 一个有给定的属性的 getter, 另外一个有 给定的属性的 setter, 但是 我使用 BeanUtils.copyProperties 的时候 把来源对象的这个属性 复制不到 目标对象上面 然后 当时也跟踪了一下代码, 然后 这里整理一下 改代码片段吧 然后在调试的过程中 也发现了一些其他的问题, 呵呵 算是额外的了解吧

  • BeanUtils.copyProperties使用总结以及注意事项说明

    目录 1.前言 2.一般使用 3.拷贝属性时忽略空值 4.使用注意事项(1) 5.使用注意事项(2) 6.使用注意事项(3) 1.前言 开发过程中,讲一个对象的属性和值赋值到另一个对象上,大量使用了get.set方法,看着很臃肿,思考下肯定不只有我有这种想法,所以技术上肯定有方法能解决这个问题,所以查阅了一些资料发现了BeanUtils.copyProperties这个方法以下是这次所有的总结以及使用时的注意事项. 使用org.springframework.beans.BeanUtils.co

  • 基于Beanutils.copyProperties()的用法及重写提高效率

    目录 Beanutils.copyProperties()用法及重写提高效率 一.简介 二.用法 三.重写 原理 BeanUtils.copyProperties 使用注意 示例演示 开始进行示例 最后强调 Beanutils.copyProperties()用法及重写提高效率 特别说明本文介绍的是Spring(import org.springframework.beans.BeanUtils)中的BeanUtils.copyProperties(A,B)方法.是将A中的值赋给B.apache

  • 聊聊BeanUtils.copyProperties和clone()方法的区别

    目录 首先,BeanUtils有两种: 效率: 需要在pom文件中引入这个包 在pom文件里面引入所需要的包 新建一个实体类StudentEntity实现Cloneable接口 测试方法 最近撸代码的时候发现有人将一个对象的值赋给另一个对象的时候,并没有使用常规的set/get方法去给对象赋值,而是采用BeanUtils.copyProperties(A,B)这个方法去赋值,但是有的还是有局限性,比如Date类型的值无法赋值,只能赋值为null,所以我大致百度了一下,作为记录. 首先,BeanU

  • BeanUtils.copyProperties()所有的空值不复制问题

    目录 BeanUtils.copyProperties()所有的空值不复制 第一种情况 第二种情况 BeanUtils.copyProperties()的用法和注意点 属性为null也会被复制,内部类不会复制过去 注意点一 注意点二 BeanUtils.copyProperties()所有的空值不复制 第一种情况 所有为空值的属性都不copy 直接上代码吧~ public class UpdateUtil { /** * 所有为空值的属性都不copy * * @param source * @p

随机推荐