天天看点

BeanUtils工具包操作JavaBean

我们在操作JavaBean的时候 我们可以用Introspector的方式来操作,但是呢这样需要我们写大量的代码 。 

Apache小组为我们提供了很有用的工具包来操作JavaBean    也就是BeanUtils工具包 ,这个可以到 apache.org 上面下载 commons-BeanUtils工具包,同时我们也要下载Logging也就是日志工具包 。   

我们下载好了BeanUtils工具包之后 打开之后 发现你面有一个docs  那个就是帮助文档 介绍了 Beanutils工具包中各种类的使用 ,这里 我们主要用到BeanUtils类 

BeanUtils类中的所有方法都是静态方法 我们通过它的getProperty  setProperty方法  等等方法    这里我们主要用到BeanUtils类 

首先我们应该将jar包加入到Eclipse的BuildPath中    然后我们才能使用BeanUtils工具包中的各种类 

下面是一个简单的JavaBean

package me.test;

import java.util.Date;

public class BeanTest

{

  private int x  ;

  private Date birthday=new Date() ;

  public BeanTest(int x)

  {

   this.x=x ;

  }

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

public Date getBirthday() {

return birthday;

public void setBirthday(Date birthday) {

this.birthday = birthday;

下面是操作

import java.lang.reflect.InvocationTargetException;

import java.util.*;

import org.apache.commons.beanutils.BeanUtils;

public class Test

   public static  void main(String []args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException

   {

    BeanTest t=new BeanTest(6)  ;

    BeanUtils.setProperty(t,"x", 7);//设置x属性   ,利用BeanUtils设置值的时候 值可以是任意原始类型 也可以是String类型  在web开发中我们用到的都是String类型 因为网页间传递的是字串 如果我们不想进行字符串转换 那个就用 PropertyUtils类 和  BeanUtils类有着同样的作用只不过 PropertyUtils 不进行类型的转换

    System.out.println(BeanUtils.getProperty(t,"x"));   //返回x属性

    BeanUtils.setProperty(t,"birthday.year", "111") ;  //这是birthday的year的属性值

    System.out.println(BeanUtils.getProperty(t,"birthday.year"));  //BeanUtils可以进行级联设置

    Map m=BeanUtils.describe(t);    //将JavaBean的各种属性以及值以Map的形式描述

   }

继续阅读