常用工具-字段拷贝赋值
– 用于相同字段值的考培拷贝(不同字段解决方案请往下看)
BeanUtils的copyProperties()方法有四种重载方式
1.copyProperties(Object source, Object target)
2.copyProperties(Object source, Object target, Class<?> editable)
3.copyProperties(Object source, Object target, String… ignoreProperties)
4.copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String… ignoreProperties)
参数有四种:
1.Object source ——数据源(不可空)
2.Object target ——目标对象(不可空)
3.Class<?> editable ——目标对象的限制类型(是否instansof)
4.@Nullable String… ignoreProperties—— 需要忽略的字段(可空、可多个)
1.简单运用
import org.springframework.beans.BeanUtils;
public class myTestCopy(){
//方法一.将旧用户对象中同名数据拷贝到新对象中
BeanUtils.copyProperties(oldUser,newUser);
//方法二.同1方法,并且People.isInstance(newUser)为true
//否则将抛出异常:throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
BeanUtils.copyProperties(oldUser,newUser,People.class);
//方法三.同1方法,并且忽略字段"name"、"age"
BeanUtils.copyProperties(oldUser,newUser,"name","age");
//方法四.同2+3,不做赘述
}
2.加强运用
? 当我想拷贝不同名的值时该怎么办呢
可以建立中间对象做转换,还能省略上述忽略字段的繁琐
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
/**
* 例:userId 为查询条件,object为我的目标对象
*/
public Boolean perfectMyInformation(String userId, Object object){
try {
//1.根据传入条件查询数据
UserDo userDo = getUserInfoById(userId);
if(ObjectUtils.isNotEmpty(userDo)){
//中间工具对象,其中包含我想转换的字段(字段名称同目标对象)
ZJUtil z = new ZJUtil();
//2.1 赋值不同名字段
z.setNewName(userDo.getName());
//2.2 赋值同名字段
BeanUtils.copyProperties(userDo,z);
//3.将中间对象和目标对象 的同名值拷贝
BeanUtils.copyProperties(z,object);
}
return true;
} catch (BeansException e) {
log.error("perfectMyInformation fault !");
return false;
}
}
小结
· 利用只能转换同名方法自定义工具方法,能完成更多需求。