BeanUtils中copyProperties的使用

BeanUtils中copyProperties的作用是将一个对象中的属性值赋值(拷贝)给另一个对象中对应的属性,并且对象之间可以没有任何联系。其中赋值成功的属性对应的属性名和属性类型必须相同,否则对应的属性值不会从一个对象赋值给另一个对象,但是此时不影响其他属性值的拷贝。具体如下所示。

1、实体类

public class Model01 {
    private String name;
    private int age;
    private String city;

    @Override
    public String toString() {
        return "Model01{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                '}';
    }
}
public class Model02 {
    private String name;
    private String age;
    private String city;

    @Override
    public String toString() {
        return "Model02{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}


2、将符合条件的属性值全部从一个对象赋值给另一个对象——copyProperties(Object source, Object target)

public class App {
    public static void main( String[] args ) {
        Model01 model01 = new Model01();
        Model02 model02 = new Model02();
        model01.setName("jack66");
        model01.setAge(12);
        model01.setCity("gz");
        model02.setName("henry");
        model02.setAge("32");
        model02.setCity("sz");
        BeanUtils.copyProperties(model01,model02);
        System.out.println(model01);
        System.out.println(model02);
    }
}
打印结果

Model01{name='jack66', age=12, city='gz'}
Model02{name='jack66', age='32', city='gz'}

3、忽略某些属性的赋值——copyProperties(Object source, Object target, String... ignoreProperties)

public class App {
    public static void main( String[] args ) {
        Model01 model01 = new Model01();
        Model02 model02 = new Model02();
        model01.setName("jack66");
        model01.setAge(12);
        model01.setCity("gz");
        model02.setName("henry");
        model02.setAge("32");
        model02.setCity("sz");
        String[] ignoreProperties = {"name"};
        BeanUtils.copyProperties(model01,model02,ignoreProperties);
        System.out.println(model01);
        System.out.println(model02);
    }
}
打印结果

Model01{name='jack66', age=12, city='gz'}
Model02{name='henry', age='32', city='gz'}

你可能感兴趣的:(java基础,【java】)