反射实体Bean 拷贝实体Bean数据

本文介绍了一个使用Java实现的对象复制示例,通过反射机制遍历源对象的所有属性,并将其复制到目标对象中。此方法适用于拥有相同属性类型的两个对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public class MyMethod {

private static class MethodBean {
private int MethodId;
private String MethodName;

public int getMethodId() {
return MethodId;
}

public void setMethodId(int methodId) {
MethodId = methodId;
}

public String getMethodName() {
return MethodName;
}

public void setMethodName(String methodName) {
MethodName = methodName;
}
}

protected MethodBean createMethodBean(int id, String name) {
MethodBean bean = new MethodBean();
bean.setMethodId(id);
bean.setMethodName(name);
return bean;
}

/**
* copy object1's data to object2
*/
protected void CopyBean(Object object1, Object object2)
throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
BeanInfo beanInfo1 = Introspector.getBeanInfo(object1.getClass());
BeanInfo beanInfo2 = Introspector.getBeanInfo(object2.getClass());

//获得 object1 beans PropertyDescriptor
PropertyDescriptor[] descriptors1 = beanInfo1.getPropertyDescriptors();
//获得 object2 beans PropertyDescriptor
PropertyDescriptor[] descriptors2 = beanInfo2.getPropertyDescriptors();

for (PropertyDescriptor descriptor1 : descriptors1) {
for (PropertyDescriptor descriptor2 : descriptors2) {
if (descriptor1.getName().equals(descriptor2.getName())) {
//获得应该用于读取属性值的方法。
Method readMethod = descriptor1.getReadMethod();
//获得应该用于写入属性值的方法。
Method writeMethod = descriptor2.getWriteMethod();
if (readMethod == null || writeMethod == null)
continue;
//对带有指定参数的指定对象调用由此 Method 对象表示的基础方法。
Object object = readMethod.invoke(object1);
writeMethod.invoke(object2, object);
continue;
}
}
}
}

public static void main(String[] args) throws IntrospectionException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
MyMethod myMethod = new MyMethod();

MethodBean bean_1 = myMethod.createMethodBean(2008, "MyMethod One");
MethodBean bean_2 = new MethodBean();
myMethod.CopyBean(bean_1, bean_2);

System.out.println("object1 id = " + bean_1.getMethodId());
System.out.println("object1 name = " + bean_1.getMethodName());

System.out.println("object2 id = " + bean_2.getMethodId());
System.out.println("object1 name = " + bean_2.getMethodName());
}
}

打印结果:
object1 id = 2008
object1 name = MyMethod One
object2 id = 2008
object1 name = MyMethod One
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值