---------------------- android培訓 java培訓
期待與您交流! ----------------------
用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;
- }
- }