BeanUtils的使用

BeanUtils可以方便快捷的操作的JavaBean对象。

需要的jar包:commons-beanutils-1.8.3.jar和commons-logging-1.1.3.jar


JavaBean对象:

public class Student implements Serializable{

	private static final long serialVersionUID = 1L;
	/*学生id*/
	private Integer sid;
	/*学生名字*/
	private String sname;
	/*学生出生日期*/
	private Date birthday;
	
	/*无参构造函数*/
	public Student() {
	}

	/*构造函数*/
	public Student(Integer sid, String sname, Date birthday) {
		this.sid = sid;
		this.sname = sname;
		this.birthday = birthday;
	}

	public Integer getSid() {
		return sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	
	
}

测试类【相关知识点和应用我都写在注释里了】:

public class BeanUtilsTest {

	public static void main(String[] args) throws Exception, InvocationTargetException {

		/* 创建一个Student对象 */
		Student stud = new Student();
		
		
/*********************** 设置某一个字段的值 **************************/
		BeanUtils.setProperty(stud, "sname", "习近平");
		System.out.println(stud.getSname());

		/* BeanUtils可以将String类型的参数自动转换为基本数据类型 */
		String sid = "123";
		/* 设置Sid【BeanUtils可以将一个字符串类型转换为Integer类型,这是一个重要的应用:WEB中表单提交的都是字符串,用这种方式,在后台都不用进行类型转换】 */
		BeanUtils.setProperty(stud, "sid", sid);
		System.out.println(stud.getSid());
		
		
		
/***********将一个字符串类型转换为复杂类型如:String类型转换为Date类型**********/
		String date = "1992-07-17";
		
		/*自定义类型转换器*/
		ConvertUtils.register(new Converter() {
			
			@Override
			public Object convert(Class type, Object value) {
				
				if (value == null){
					return null;
				}
				if (!(value instanceof String)){
					throw new ConversionException("只支持字符串的转换!");
				}
				
				String str = (String) value;
				if (str.trim().equals("")){
					return null;
				}
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					return sdf.parse(str);
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
		}, java.util.Date.class);
		
		/*设置经过转换之后的日期类型*/
		BeanUtils.setProperty(stud, "birthday", date);
		
		System.out.println(stud.getBirthday());
		
		
		
/************************将一个map集合快速导入到bean中**********************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sid", "113285");
		map.put("sname", "廖泽民");
		/*一次性导入一个map集合*/
		BeanUtils.populate(stud, map);
		
		System.out.println(stud.getSname());
		
	}

}



你可能感兴趣的:(BeanUtils,javabean)