1. beanutils 简介
beanutils工具包有apache进行开发,主要是方便程序员对JavaBeans进行操作。实际上beanutils底层是利用了发射机制去操作JavaBeans。
beanutils底层去操作JavaBeans的属性时,是通过调用JavaBeans的getter和setter方法进行设值和获取的。
2. 搭建环境
2.1 下载工具包
commons-beanutils工具包的下载地址:http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi
由于commons-beanutils工具包依赖于commons-logging工具包,则必须将commons-logging工具包一通包含于项目中。
2.2 导入工具包
1)将commons-beanutils与commons-logging解压
2) 将commons-beanutils-1.9.1.jar和commons-logging-1.2.jar加入到项目中
a) 右击 点击 “Build Path”,然后选择 "Configure Build Path"
b) 加入 commons-beanutils 和 commons-logging 的 jar 包
3. 开发示例
3.1 创建一个Person类
/***************************************************************************
* @filename Person.java
* @date 2016年8月16日 上午11:38:59
* @author liuxuandong
* @email 1004319075@qq.com
* @version 1.0
* @description
**************************************************************************/
package com.lxd.beanutilsdemo;
public class Person {
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
3.1 测试beanutils工具包中BeanUtils类中的setProperty()方法和getProperty()方法
/***************************************************************************
* @filename TestBeanUtils.java
* @date 2016年8月16日 下午12:56:26
* @author liuxuandong
* @email 1004319075@qq.com
* @version 1.0
* @description
**************************************************************************/
package com.lxd.beanutilsdemo;
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
public class TestBeanUtils {
@Test
public void test1() throws IllegalAccessException, InvocationTargetException {
Object object = new Person();
BeanUtils.setProperty(object, "id", "1107");
BeanUtils.setProperty(object, "name", "lxd");
BeanUtils.setProperty(object, "age", 24);
System.out.println(object);
}
@Test
public void test2() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object object = new Person("0212", "zhh", 24);
System.out.println(object);
String id = BeanUtils.getProperty(object, "id");
String name = BeanUtils.getProperty(object, "name");
int age = Integer.parseInt(BeanUtils.getProperty(object, "age"));
System.out.println("id = " + id);
System.out.println("name = " + name);
System.out.println("age = " + age);
}
}
3.2 示例输出结果
1) test1()
2) test2()