用BeanUtils工具包时,先要把两个Jar包进行Building Path,就是引入两个jar包,
commons-beanutils.jar
commons-logging-1.1.jar
package com.base_super;
import java.util.Date;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
/**
* Apache 提供的BeanUtils工具包
*
* @author zjw
*
*/
public class BeanUtils_class {
public static void main(String[] args)throws Exception {
methiod();
}
public static void methiod() throws Exception {
JavaBean_BeanUtils_class bean=new JavaBean_BeanUtils_class(33,44);
//如果用BeanUtils调用的JavaBean 一定要用public修饰,要不然报错
System.out.println(BeanUtils.getProperty(bean,"b"));//其他数据类型都自动转换为字符串类型,进行输入输出
System.out.println(BeanUtils.getProperty(new JavaBean_BeanUtils_class(333,888),"a"));
BeanUtils.setProperty(bean,"str","aaaaaaaaaaaaaaaaaaaaaa");//通过BeanUtils设置JavaBean的值
System.out.println(bean.getStr());
//BeanUtils支持属性链
Date d=new Date();
// d.setHours(hours);
// d.setMinutes(minutes);
// d.setMonth(month);
// d.setSeconds(seconds);
// d.setYear(year);
// d.setTime(time);
// d.setDate(date);
// d.getDay();//这个getDay不行,所以一般用属性链时,最好用set方法的属性(自我总结)
//Date中封装了这些个属性,都可以用做属性链,但每个属性都有自己的长度等限制,用时小心点
BeanUtils.setProperty(bean,"birthday.time","333333");
System.out.println(BeanUtils.getProperty(bean,"birthday.time"));
/*
* Map和JavaBean都是属性,值的组合方式,很相似,可以同过BeanUtils工具相互转换
*
*/
//这是JDK1.7的新特性,Map的新的定义方式
// Map map={name:"wjw",age:23};
// System.out.println(BeanUtils.setProperty(map,"name","wjw_java"));//BeanUtils也可以对Map进行操作
/*
* BeanUtils以字符串类型进行操作
* PropertyUtils以数据本身的类型进行操作
*/
PropertyUtils.setProperty(bean,"str","3331111");//str本身是字符串类型
System.out.println(PropertyUtils.getProperty(bean,"str"));
PropertyUtils.setProperty(bean,"a",99999999);//a本身是整形数据类型
System.out.println(PropertyUtils.getProperty(bean,"a"));
}
}
对应的JavaBean
package com.base_super;
import java.util.Date;
public class JavaBean_BeanUtils_class{
private int a;
private int b;
private String str="dddddddd";
private Date birthday =new Date();//实例化对象,用BeanUtils就可以使用Date中的属性了
public JavaBean_BeanUtils_class(int a,int b){
this.a=a;
this.b=b;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}