BeanUtils使用將一個對象拷貝到另外一個對象

1
參考文檔 = https://www.cnblogs.com/mkdlf/p/7234906.html?utm_source=itdadao&utm_medium=referral

這裏的BeanUtils是BeanUtils是org.springframework.beans.BeanUtils,和org.apache.commons.beanutils.BeanUtils是有區別的
BeanUtils.copyProperties(ojb, tarObj, “id”,“ver”);
將obj的字段拷貝到tarObj中,除了id和ver,第三個字段之後是可變參數,用來指定哪些字段不用拷貝

public void test() throws Exception
    {
        //1.生成對象
        Student s1 = new Student();
        Student s2 = new Student();
        
        //2.通過set方法賦值
        s1.setId(1);
        s1.setName("VN");
        //s1.setAge(19);//基本數據類型可以爲null,null也能拷貝
        s1.setClassID(5);
        s1.setBirthday(new Date());//特殊類型不能爲null

        //需求:把s1的屬性值拷貝到S2中,
        //注意參數的順序,第三個參數之後爲可選參數,指定哪些字段不用拷貝
        BeanUtils.copyProperties(s1, s2,"id");
        
        System.out.println(s1);
        System.out.println(s2);    
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章