BeanUtils. copyProperties Extension Realizing String to Date
- 2021-09-16 07:16:55
- OfStack
BeanUtils. copyProperties (target, source) and PropertyUtils. copyProperties (target, source) both copy the value of the attribute of the source object into the same attribute name of the target object.
The difference is:
BeanUtils.copyProperties(target,source)
Support type conversion between base types, String, java. sql. Date, java. sql. Timestamp, java. sql. Time, that is, copying is successful as long as the attribute names of these types are the same. However, the property value is initialized by default. Note: Conversion of java. util. Date type is not supported and needs to be set manually.
PropertyUtils.copyProperties(target,source)
Type conversion is not supported, but the property value is not initial, allowing the property value to be null.
An String type was encountered in webservice, but the database is of java. util. Date type, so an error is reported when using PropertyUtils. copyProperties (target, source) because there are not many object attributes.
Later, I checked the data and said that BeanUtils can convert types, so I customized a tool class from String to Date.
Defining a tool class
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 {
// Registration util.date That is, the converter that allows BeanUtils.copyProperties Of the source target when the util Values of type are allowed to be null
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 {
// Support for dates copy
org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
}
}
Define the date conversion format
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;
}
}
When BeanUtilsEx and copyProperties (target, source) are used, String can be converted into Date.
In addition, if there are few attributes to be converted, you can take out the conflicting attributes in source object first, save one copy, and then set the attribute value to null, because null attributes will not be copied, so there will be no mistakes when copying. When the copy is completed, the conflicting attributes are converted into the required format, and set is entered into the target object. This is also the realization effect.
The test code is as follows:
Target object 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 + "]";
}
}
Source object 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 + "]";
}
}
Test code
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")) {// For attribute names, do not 1 Sample attributes will not be assigned, and need to be set manually
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 Date to Character Date to Long
Create your own date conversion class
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);
}
}
}
Use your own date conversion class instead of the default. Such as the following main function
public static void main(String[] args) {
// Replace
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());
}