package com.zyhao.openec.catalog.pojo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 将 A(bean)中的值copy到B(bean)
* 注意:1,必须是同一个实体类
* 2.两个不同的对象
* 3.属性只能包含有get和set方法的类
* @author Administrator
*
*/
public class BeanCopyUitl {
public static void reflectAbeanToBbean(Object class1,Object class2) throws NoSuchMethodException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 获取实体类的所有属性,返回Field数组
Field[] field1 = class1.getClass().getDeclaredFields();
Field[] field2 = class2.getClass().getDeclaredFields();
for (int i = 0; i < field1.length; i++) {
// 获取属性的名字
String name = field1[i].getName();
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
Method m1 = class1.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Object value = m1.invoke(class1);
if (value != null) {
Field f = field2[i];
f.setAccessible(true); //设置些属性是可以访问的
// Object val = f.get(class2);//得到此属性的值
f.set(class2,value) ; //给属性设值
}
}
}
/* public static void main(String[] args) throws Exception {
Date date = new Date();
UserInfo u1 = new UserInfo("123","caiyong", 18, date);
UserInfo u2 = new UserInfo(null,"", 1898, null);
reflectTest1(u1,u2);
System.out.println(u2.toString());
}*/
}
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 将 A(bean)中的值copy到B(bean)
* 注意:1,必须是同一个实体类
* 2.两个不同的对象
* 3.属性只能包含有get和set方法的类
* @author Administrator
*
*/
public class BeanCopyUitl {
public static void reflectAbeanToBbean(Object class1,Object class2) throws NoSuchMethodException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 获取实体类的所有属性,返回Field数组
Field[] field1 = class1.getClass().getDeclaredFields();
Field[] field2 = class2.getClass().getDeclaredFields();
for (int i = 0; i < field1.length; i++) {
// 获取属性的名字
String name = field1[i].getName();
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
Method m1 = class1.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Object value = m1.invoke(class1);
if (value != null) {
Field f = field2[i];
f.setAccessible(true); //设置些属性是可以访问的
// Object val = f.get(class2);//得到此属性的值
f.set(class2,value) ; //给属性设值
}
}
}
/* public static void main(String[] args) throws Exception {
Date date = new Date();
UserInfo u1 = new UserInfo("123","caiyong", 18, date);
UserInfo u2 = new UserInfo(null,"", 1898, null);
reflectTest1(u1,u2);
System.out.println(u2.toString());
}*/
}