需求
在字段名相同的情况下,但是对于数据类型不一致,需要将Date类型转化为LocalDateTime类型。由于BeanUtils中默认转化器不支持,因此自定义转化器,且改类型转化器只在当前类中生效。
1.自定义的类型转化器
package com.raycloud.kmkf.basic.converter;
import org.apache.commons.beanutils.Converter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
/**
* 自定义Apache中BeanUtils转化器
*
* @author bingyou
* @since 2024/7/31 15:48
*/
public class DateToLocalDateTimeConverter implements Converter {
/**
* Date类型转化为LocalDateTime类型
*
* @param type 返回值Class类型
* @param value 输入值
* @return 返回值类型
*/
@Override
@SuppressWarnings("unchecked")
public LocalDateTime convert(Class type, Object value) {
if (Objects.isNull(type) || Objects.isNull(value)) {
return null;
}
if (Objects.equals(LocalDateTime.class, type)) {
if (value instanceof Date) {
return ((Date) value).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
if (value instanceof LocalDateTime) {
return (LocalDateTime) value;
}
}
return null;
}
}
2.如何使用
2.1注册自定义转化器【对整个类生效】
/**
* 自定义BeanUtils属性拷贝类型转化器
*/
private static final DateToLocalDateTimeConverter CONVERTER = new DateToLocalDateTimeConverter();
static {
// 注册自定义转化器,第二个参数为目标类属性类型
ConvertUtils.register(CONVERTER, LocalDateTime.class);
}
2.2在该类中使用BeanUtils.copyPropertie()方法
@NotNull
private static ApplyTime convertToApplyTime(Object applyTimeSource) {
ApplyTime applyTime = new ApplyTime();
try {
// 将appTimeSource中属性拷贝到appTime中支持【Date --> LocalDateTime】
BeanUtils.copyProperties(applyTime, applyTimeSource);
} catch (Exception e) {
throw new RuntimeException(e);
}
return applyTime;
}
3.说明
1.对于无特殊类型类型转化,建议使用Spring中的BeanUtils类,拷贝效率更高
2.由于Spring中的自定义转化器,针对全局生效,无法指定具体类。不满足我的需求,因此未使用。
3.对于使用频率极高的接口,不建议使用Apache中BeanUtils拷贝,可能存在性能问题,建议自己写个反射实现。