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

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: