How to use BeanUtils.copyProperties

BeanUtils.copyProperties() is a method in the Apache Commons BeanUtils library used to copy the property values of one Java object to another Java object’s corresponding properties.

Method signature:

public static void copyProperties(Object dest, Object orig)

Explanation of parameters:

  1. Target object: The property values will be copied to this object.
  2. source object, the attribute values will be copied from this object.

Important points to consider:

  1. This method will automatically copy the property values of the source object to the corresponding properties in the target object based on the property name and type.
  2. If the property names and types of two objects match exactly, the property values will be directly copied; if the property names do not match, the method will attempt to perform type conversion, and if the conversion fails, an exception will be thrown.
  3. This method will recursively copy nested object properties.

Sample code:

public class User {
    private String name;
    private int age;
    // getter和setter方法省略
}

public class UserDTO {
    private String name;
    private int age;
    // getter和setter方法省略
}

public static void main(String[] args) {
    User user = new User();
    user.setName("John Doe");
    user.setAge(30);

    UserDTO userDTO = new UserDTO();
    BeanUtils.copyProperties(userDTO, user);

    System.out.println(userDTO.getName()); // 输出:John Doe
    System.out.println(userDTO.getAge());  // 输出:30
}

The example above illustrates how to copy the property values of a User object to a UserDTO object. By calling the BeanUtils.copyProperties() method, the property copy operation can be conveniently completed.

bannerAds