Using BeanUitls to Improve Object Copying Efficiency

Keywords: Java Apache Attribute Spring

First, create two bean s
Note: There must be set/get methods, and member variables must have the same name.

public class User1 {
    String name;
    String password;
    String phone;
/**Omitting get/set method**/
}
public class User2 {
    String name;
    String password;
    String phone;
/**Omitting get/set method**/
}

1.Spring's Bean Utils (easy to use)

org.springframework.beans.BeanUtils

BeanUtils. copyProperties (source object, target object)
Test methods:

public static void main(String[] args){
        User1 user1=new User1();
        user1.setName("user1_name");
        user1.setPassword("user1_password");
        user1.setPhone("user1_phone");
        User2 user2=new User2();
        BeanUtils.copyProperties(user1,user2);
        System.out.println(user2.toString());
    }

Implementation results:

User2(name=user1_name, password=user1_password, phone=user1_phone)
Note: It is necessary to ensure that the two member variables of the same name have the same type. One attribute of the same name is the packaging type, and the other is the non-packaging type.

2.Apache's Bean Utils (extensible, relatively complex)

org.apache.commons.beanutils.BeanUtils

BeanUtils. copyProperties (target object, source object)
Need to introduce dependencies

    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.3</version>
    </dependency>

Test methods:

public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        User1 user1=new User1();
        user1.setName("user1_name");
        user1.setPassword("user1_password");
        user1.setPhone("user1_phone");
        User2 user2=new User2();
        BeanUtils.copyProperties(user2,user1);
        System.out.println(user2.toString());
    }

Implementation results:

User2(name=user1_name, password=user1_password, phone=user1_phone)

commons-beanutils impose a lot of checks, including type conversion, and even the accessibility of the class to which the object belongs. BeanUtils can successfully replicate object attribute values, depending on its type recognition.

Reference https://www.jianshu.com/p/9b4f81005eb7

Posted by vivianp79 on Tue, 26 Mar 2019 22:12:30 -0700