BeanUtils工具包操作JavaBean

简介: 我们在操作JavaBean的时候 我们可以用Introspector的方式来操作,但是呢这样需要我们写大量的代码 。  Apache小组为我们提供了很有用的工具包来操作JavaBean    也就是BeanUtils工具包 ,这个可以到 apache.org 上面下载 commons-BeanUtils工具包,同时我们也要下载Logging也就是日志工具包 。

我们在操作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;
}
 
}
下面是操作

package me.test;
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的形式描述
   

   }

}

 

目录
相关文章
|
7月前
|
IDE Java 数据库
Java实体映射工具MapStruct
Java实体映射工具MapStruct
101 0
|
7月前
BeanUtils的忽略字段工具类
BeanUtils的忽略字段工具类
58 0
|
28天前
|
缓存 安全 Java
你还在用 BeanUtils?试试 MapStruct,优雅的对象转换解决方案
你还在用 BeanUtils?试试 MapStruct,优雅的对象转换解决方案
27 0
|
3月前
|
JSON fastjson 数据格式
JSON转换常用类库
JSON转换常用类库
|
4月前
|
Java Apache Spring
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
61 0
|
Java API Apache
BeanUtils开发包的使用
BeanUtils开发包的使用
145 0
BeanUtils开发包的使用
|
JavaScript 前端开发 Java
实体映射最强工具类:MapStruct 真香!
实体映射最强工具类:MapStruct 真香!