反射实体Bean 拷贝实体Bean数据
程序员文章站
2022-03-03 12:32:12
...
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
上一篇: python如何去除字符串中不想要的字符
下一篇: 图(深度优先遍历、广度优先遍历)