题目描述:通过反射赋值源对象中的属性值到目标对象的具有相同类型和名称的属性
public class BeanUtils { /** * 对象的属性值拷贝 * <p> * 将source对象中的属性值赋值到target对象中的属性,属性名一样,类型一样 * <p> * example: * <p> * source: * <p> * String name; * String address; * Integer age; * Date birthday; * <p> * target: * String name; * String address; * String email * <p> * 结果: source name, address -> target name, address * * @param source * @param target */ public static void copy(Object source, Object target) { //TODO } } public class BeanUtils { public static void copy(Object source,Object target) { //1丶参数效验 if(source == null){ throw new IllegalArgumentException("source object must be not nul"); } if(target == null){ throw new IllegalArgumentException("target object must be not null"); } //2丶获取Class对象 Class sourceCls = source.getClass(); Class targetCls = target.getClass(); //3丶获取Class对象中的Field Field[] sourceFields = sourceCls.getDeclaredFields(); Field[] targetFields = targetCls.getDeclaredFields(); //4丶通过sourceFields在targetFields找它元素相同(名字和类型) for(Field sf : sourceFields){ for(Field tf : targetFields){ if(sf.getName().equals(tf.getName()) && sf.getType() == tf.getType()){ try{ sf.setAccessible(true); tf.setAccessible(true); Object value = sf.get(source); tf.set(target,value); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } } } } public class TestBeanUtils { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setAge(28); teacher.setBirthday(new Date()); teacher.setName("jack"); Student student = new Student(); System.out.println("copy before:"); System.out.println(teacher); System.out.println(student); System.out.println("copy after:"); BeanUtils.copy(teacher,student); System.out.println(teacher); System.out.println(student); } } class Student{ private String name; private Integer age; private String skill; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", skill='" + skill + '\'' + '}'; } } class Teacher { private String name; private Integer age; private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Teacher{" + "name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } }下面是测试结果:
