cn.hutool.core.convert.impl.BeanConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hutool-all Show documentation
Show all versions of hutool-all Show documentation
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
package cn.hutool.core.convert.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.convert.AbstractConverter;
import cn.hutool.core.convert.ConvertException;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.TypeUtil;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Bean转换器,支持:
*
* Map =》 Bean
* Bean =》 Bean
* ValueProvider =》 Bean
*
*
* @param Bean类型
* @author Looly
* @since 4.0.2
*/
public class BeanConverter extends AbstractConverter {
private static final long serialVersionUID = 1L;
private final Type beanType;
private final Class beanClass;
private final CopyOptions copyOptions;
/**
* 构造,默认转换选项,注入失败的字段忽略
*
* @param beanType 转换成的目标Bean类型
*/
public BeanConverter(Type beanType) {
this(beanType, CopyOptions.create().setIgnoreError(true));
}
/**
* 构造,默认转换选项,注入失败的字段忽略
*
* @param beanClass 转换成的目标Bean类
*/
public BeanConverter(Class beanClass) {
this(beanClass, CopyOptions.create().setIgnoreError(true));
}
/**
* 构造
*
* @param beanType 转换成的目标Bean类
* @param copyOptions Bean转换选项参数
*/
@SuppressWarnings("unchecked")
public BeanConverter(Type beanType, CopyOptions copyOptions) {
this.beanType = beanType;
this.beanClass = (Class) TypeUtil.getClass(beanType);
this.copyOptions = copyOptions;
}
@Override
protected T convertInternal(Object value) {
final Class>[] interfaces = this.beanClass.getInterfaces();
for (Class> anInterface : interfaces) {
if("cn.hutool.json.JSONBeanParser".equals(anInterface.getName())){
// issue#I7M2GZ
final T obj = ReflectUtil.newInstanceIfPossible(this.beanClass);
ReflectUtil.invoke(obj, "parse", value);
return obj;
}
}
if(value instanceof Map ||
value instanceof ValueProvider ||
BeanUtil.isBean(value.getClass())) {
if(value instanceof Map && this.beanClass.isInterface()) {
// 将Map动态代理为Bean
return MapProxy.create((Map, ?>)value).toProxyBean(this.beanClass);
}
//限定被转换对象类型
return BeanCopier.create(value, ReflectUtil.newInstanceIfPossible(this.beanClass), this.beanType, this.copyOptions).copy();
} else if(value instanceof byte[]){
// 尝试反序列化
return ObjectUtil.deserialize((byte[])value);
} else if(StrUtil.isEmptyIfStr(value)){
// issue#3136
return null;
}
throw new ConvertException("Unsupported source type: {}", value.getClass());
}
@Override
public Class getTargetType() {
return this.beanClass;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy