BeanUtils低依赖属性拷贝测试(一)

javabean

package entity;

import java.util.Date;
/**
 * 一个测试用:
 * 		student,javaBean
 * @author mzy
 *		一个标准的javaBean:
 *			1) 属性只要是private修饰的;
 *			2) 提供setter和getter方法;
 *			3) 提供无参构造。
 *		就行了;有参构造等不是必须的。
 */
public class Student {
	private int id;
	private String name;
	private double score;
	private boolean gender;
	private Date birth;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", score=" + score + ", gender=" + gender + ", birth=" + birth
				+ "]";
	}
}

属性拷贝测试:

package beanutil;

import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;

import entity.Student;

/**
 * 我发现很多包都有commons-xxx,后面知道commons在很多Apache的项目中会使用
 * 一般commons都是apache公司的产品。
 * 		其中dbutils是实际使用的包;
 * 		logging是日志文件。
 * 
 * @author mzy
 * 
 * dbutils:
 * 		从一个javaBean对象中拷贝属性
 * 		把一个javaBean对象的属性拷贝到另一个javaBean对象中
 * 		从一个map中把属性拷贝到javaBean对象中
 */
public class Demo01 {
	public static void main(String[] args) throws Exception {
		/*
		 * 1) 拷贝一个javabean对象的属性
		 */
		Student s = new Student();
		s.setId(1);
		s.setName("mzy");
		s.setScore(99.99);
		s.setGender(true);
		s.setBirth(new Date());
		
		// 1) 把id,name属性值从s对象拷贝到s2的对象中
		
		// Student s2 = new Student();
		// s2.setId(s.getId());
		
		Object s2 = Class.forName("entity.Student").newInstance();
		
		/**
		 * bean:拷贝到的bean对象;
		 * name:拷贝的属性名称(可以另取);
		 * value:拷贝的值;
		 * 
		 * 使用BeanUtils的好处是:
		 * 		在进行拷贝的时候,依赖性低;
		 * 		不像上面通过set,get方法如果立即报错!(相互之间依赖性高)
		 */
		BeanUtils.copyProperty(s2, "id", "1");
		
		BeanUtils.copyProperty(s2, "id", s.getId()); // 不需要依赖于Student对象
		
		System.out.println(s);
		System.out.println(s2);
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36791569/article/details/80271552
今日推荐