public static void main(String[] args) throws Exception {
PersonInfo personInfoA = new PersonInfo(); personInfoA.setName("tiger"); personInfoA.setAge(28); PersonInfo personInfoB = new PersonInfo(); copyProperties(personInfoB, personInfoA); personInfoB.setName(personInfoB.getName()+"temp"); personInfoB.setAge(personInfoB.getAge()+1); System.err.println(personInfoA.toString()); System.err.println(personInfoB.toString());
public static void copyProperties(Object personInfoB , Object personInfoA ) throws Exception{ BeanInfo beanInfo = Introspector.getBeanInfo(personInfoA.getClass()); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { PropertyDescriptor srcProp = props[i]; // 获取对应的属性信息 PropertyDescriptor destProp = findProperty(personInfoB, srcProp.getName()); if ((destProp != null) && (destProp.getWriteMethod() != null) && (srcProp.getReadMethod() != null)) try { // 找到源对象属性值 Object srcVal = srcProp.getReadMethod().invoke(personInfoA, new Object[0]); // 调用目标对象的属性赋值方法,实现属性值复制 destProp.getWriteMethod().invoke(personInfoB, new Object[] { srcVal }); } catch (Exception ex) { } } } public static class PersonInfo { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } private static PropertyDescriptor findProperty(Object object, String name) throws IntrospectionException { // 通过内省工具类获取属性信息 BeanInfo info = Introspector.getBeanInfo(object.getClass()); // 获取属性描述信息 PropertyDescriptor[] properties = info.getPropertyDescriptors(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor property = properties[i]; if (property.getName().equals(name)) { return property; } } return null; }