JAVA对象之间属性复制BeanUtils.copyProperties

介绍

项目中有时遇到对象属性之间赋值,但是对象的赋值属性比较多的时候,会想到用BeanUtils.copyProperties进行拷贝

使用方法

 BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。

	public static void copyProperties(Object source, Object target) throws BeansException {
		copyProperties(source, target, null, (String[]) null);
	}

User对象

public class User(){
    
    private String name;
    private int age;
    
    
    set/get/toString 

}

我们通过BeanUtils.copyProperties进行拷贝User对象中的属性值


import org.springframework.beans.BeanUtils;
/**
 * Created by WXD
 * 2022-04-20 15:56
 */
public class demo {
    public static void main(String[] args) {
            User user1 = new User("WXD", 18);
            User user2 = new User();
            BeanUtils.copyProperties(user1, user2);
            System.out.println("用户1:" + user1);
            System.out.println("用户2:" + user2);
    }
}

 结果

 注意:当User对象中的属性没有get/set方法时,拷贝后属性值为null   !!!

源码通过targetPd.getWriteMethod()找set方法,sourcePd.getReadMethod()找get方法。

走到这readMethod.invoke(source)会调用对象属性的get方法获取属性值;然后走到writeMethod.invoke(target, value)会调用对象属性的set方法设置属性值。

for (PropertyDescriptor targetPd : targetPds) {
                        //找set方法
			Method writeMethod = targetPd.getWriteMethod();
			if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null) {
                                    //找get方法
					Method readMethod = sourcePd.getReadMethod();
					if (readMethod != null &&
							ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
						try {
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
								readMethod.setAccessible(true);
							}
                                                    //调用get方法
							Object value = readMethod.invoke(source);
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
                                                    //调用set方法
							writeMethod.invoke(target, value);
						}
						catch (Throwable ex) {
							throw new FatalBeanException(
									"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
						}
					}
				}
			}
		}

通过源码可知,BeanUtils.copyProperties通过java反射将类中当前属性字段对应的内容复制到另外一个类中,属性必须具有get/set方法,不然拷贝值为null。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值