package com.franky.bean;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
/**
* @描述 BeanUtils与PropertyUtils的使用 需要JAR包commons-beanutils.jar与commons-logging-1.1.jar
* @作者 franky
* @日期 2014-12-31 下午12:04:24
*/
public class JavaBeanTestWithBeanUtils {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Point point = new Point(5, 5);
//beanutils操作bean的属性都会转换为字符串
//利用beanutils得到bean对象的属性值
System.out.println(BeanUtils.getProperty(point, "x"));
//BeanUtils返回的是String类型
System.out.println(BeanUtils.getProperty(point, "x").getClass().getName());
//利用beanutils设置bean对象的属性值
BeanUtils.setProperty(point, "x", 10);
System.out.println(BeanUtils.getProperty(point, "x"));
//可以对非基本类型的属性进行级联操作,获取date属性中的time
//将非基本类型的属性对象同样当作bean对象操作
System.out.println(BeanUtils.getProperty(point, "date.time"));
//设置date的time属性值,BeanUtils只支持8种基本数据类型的转换,其他类型需要进行ConvertUtils.register();进行类型转换
BeanUtils.setProperty(point, "date.time", 1234567);
System.out.println(BeanUtils.getProperty(point, "date.time"));
//利用PropertyUtils进行属性值的获取,返回的值类型为属性的本类型
//而不是BeanUtils返回的都是String类型
System.out.println(PropertyUtils.getProperty(point, "x"));
//本类型为Integer
System.out.println(PropertyUtils.getProperty(point, "x").getClass().getName());
}
}
Point类:
package com.franky.bean;
import java.util.Date;
public class Point {
private int x;
private int y;
private Date date = new Date();
/**
* @return the date
*/
public Date getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date) {
this.date = date;
}
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}