工具类:对象拷贝BeanUtils(提高对象拷贝效率)

我们直接使用maven构建的项目演示:

1. 在maven的pom.xml文件中引入BeanUtils的jar包:

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

2. 新建实体类Student.java

工具类:对象拷贝BeanUtils(提高对象拷贝效率)
package com.drew.entity;

/**
 * @author zero 2019/03/24
 */
public class Student {
    private Integer stuId;
    private String stuName;

    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    @Override
    public String toString() {
        return "Student [stuId=" + stuId + ", stuName=" + stuName + "]";
    }

    /**
     * @param stuId
     * @param stuName
     */
    public Student(Integer stuId, String stuName) {
        super();
        this.stuId = stuId;
        this.stuName = stuName;
    }

    public Student() {
        super();
    }

}
Student.java

3. 新建测试类:TestBeanUtils.java

 1 package com.drew.test;
 2 
 3 import java.lang.reflect.InvocationTargetException;
 4 
 5 import org.apache.commons.beanutils.BeanUtils;
 6 
 7 import com.drew.entity.Student;
 8 
 9 /**
10  * @author zero 2019/03/24
11  */
12 public class TestBeanUtils {
13     
14     public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
15         Student student = new Student(1, "Drew");
16         Student student2 = (Student)BeanUtils.cloneBean(student);
17         System.out.println(student2);
18         
19         Student student3 = new Student();
20         BeanUtils.copyProperties(student3, student);// 第一个参数是:目标存储,第二个参数:源数据
21         System.out.println(student3);
22     }
23 
24 }

3. 测试结果:

工具类:对象拷贝BeanUtils(提高对象拷贝效率)

 

上一篇:Java反射——内省(Introspector)以及BeanUtils内省框架


下一篇:beanutils组件