编程知识 cdmana.com

Java: org.apache.commons . beanutils.BeanUtils Attribute object copy

rely on

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

Code example

Two simple things Java class


public class User {
    
    private String name;

    private Integer age;

    public String getName() {
    
        return name;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public Integer getAge() {
    
        return age;
    }

    public void setAge(Integer age) {
    
        this.age = age;
    }

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


public class Person {
    
    private String name;

    private Integer age;

    public String getName() {
    
        return name;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public Integer getAge() {
    
        return age;
    }

    public void setAge(Integer age) {
    
        this.age = age;
    }

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


import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;

public class BeanDemo {
    
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
    
        User user = new User();
        user.setAge(23);
        user.setName("Tom");

        System.out.println(user);
        // User{name='Tom', age=23}

        //  Prepare one Person object 
        Person person = new Person();

        BeanUtils.copyProperties(person, user);

        System.out.println(person);
        // Person{name='Tom', age=23}

    }
}

版权声明
本文为[Peng Shiyu]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224171911699P.html

Scroll to Top