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

猜你喜欢

转载自blog.csdn.net/qq_36791569/article/details/80271611