Java实现不同的类的属性其间相互赋值

Java实现不同的类的属性之间相互赋值

在开发的时候可能会出现将一个类的属性值,复制给另外一个类的属性值,这在读写数据库的时候,可能会经常的遇到 ,特别是对于一个有继承关系的类的时候,我们需要重写很多多余的代码,下面有一种简单的方法实现该功能,

1、首先有两个类,两个类之间有相同的属性名和类型,也有不同的属性名很类型:

public class ClassTestCopy2 {
    private int id;
    private String name;
    private String password;

    private String sex;
    private String age;
    //get和set方法
}
public class ClassTestCopy1 {
    private int id;
    private String name;
    private String password;

    //get和set方法
}

2、下边的就是实现该功能的方法体:

public static void Copy(Object source, Object dest) throws Exception {
        // 获取属性
        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();

        BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);
        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();

        try {
            for (int i = 0; i < sourceProperty.length; i++) {
                for (int j = 0; j < destProperty.length; j++) {
                    if (sourceProperty[i].getName().equals(destProperty[j].getName())) {
                        // 调用source的getter方法和dest的setter方法
                        destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("属性复制失败:" + e.getMessage());
        }
    }

3、下边进行测试:

public static void main(String[] args) {
        ClassTestCopy1 c1 = new ClassTestCopy1(1205030213, "name:xuliugen","password:123456");
        ClassTestCopy2 c2 = new ClassTestCopy2();
        try {
            CopyBeanParamsTest.Copy(c1, c2);
            System.out.println("-------------c1----------------");
            System.out.println(c2.getId());
            System.out.println(c2.getName());
            System.out.println(c2.getPassword());
            System.out.println(c2.getSex());
            System.out.println(c2.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4、测试结果如下:
Java实现不同的类的属性其间相互赋值

可知具有相同属性名和类型的属性被赋值,剩下的没有被匹配到的结果则为NUll;

版权声明:本文为博主原创文章,未经博主允许不得转载。