工具类之org.springframework.beans.BeanUtils.copyPropeties
作者:互联网
- 类所属
BeanUtils.copyProperties
的全路径名是:org.springframework.beans.BeanUtils.copyProperties
- 类作用
进行对象之间属性的赋值,避免用过get、set方法一个个属性的赋值 - 方法体
* Copy the property values of the given source bean into the target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * <p>This is just a convenience method. For more complex transfer needs, * consider using a full BeanWrapper. * @param source the source bean //源对象 * @param target the target bean //目标对象 * @throws BeansException if the copying failed //异常类型 * @see BeanWrapper */ public static void copyProperties(Object source, Object target) throws BeansException { copyProperties(source, target, null, (String[]) null); }
- 用法
/**
* @author wxj
* @date 2021年07月30日 11:56
*/
@Data
public class Father {
private String face; // 长相
private String height; // 身高
private Life life; // 生命
}
@Data
public class Life {
private String status;
}
@Data
public class Son extends Father {
private Life life;
public static void main(String[] args) {
Father zs = new Father();
zs.setFace("张三");
zs.setHeight("身高250");
Life zsLife = new Life();
zsLife.setStatus("活着");
zs.setLife(zsLife);
Son ls=new Son();
BeanUtils.copyProperties(zs,ls);
System.out.println("height:"+ls.getHeight()+" face:"+ls.getFace()+" life:"+ls.getLife());
}
}
//控制台打印
height:身高250 face:张三 life:Life(status=活着)
可以看到Father和Lif类属性赋值给了Son
5.总结
BeansUtils.copyProperties通过调用set方法完成赋值,所有是浅拷贝
标签:Life,target,copyProperties,springframework,source,bean,beans,ls,copyPropeties 来源: https://blog.csdn.net/weixin_43499806/article/details/119241657