1. 程式人生 > >BeanUtils使用:從一個map集合中,拷貝到javaBean中(四)

BeanUtils使用:從一個map集合中,拷貝到javaBean中(四)

package beanutil;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

/**
 * 從一個map集合中,拷貝到javaBean中;
 * @author mzy
 *
 */
public class Demo04 {
	public static void main(String[] args) {
		
		
		try {
			/**
			 * 3)從一個map集合中拷貝到一個javabean中
			 * 注意: 
			 * 	1)只拷貝javabean存在的哪些屬性(setXXX方法)
			 *  2)需要拷貝的資料是陣列型別,那麼只拷貝陣列中的第一個元素。
			 *
			 */
			ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class);
			Map map = new HashMap();
			//map.put("name", "jacky");
			map.put("name", new String[]{"jacky","eric"});//字串陣列
			map.put("id", "4");
			map.put("gender", "true");
			// map.put("scroe", "86.43"); // 當不符合javaBean規範的時候,就不會賦值進去,顯示的就是預設值
			map.put("score", "86.43");
			map.put("birth","2015-06-05");
			
			Object s2 = Class.forName("entity.Student").newInstance();
			
			//把一個map的資料拷貝到s2中
			BeanUtils.copyProperties(s2, map);
			
			System.out.println(s2);
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}
}

這種從map中拷貝的方式,我們可以結合servlet中的getParameterMap();

使用javabean規範簡化賦值操作!

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
				+ "]";
	}
}