commons-beanutils是通过内省来完成的。

需要两个包:

  • commons-beanutils-1.8.3.jar
  • commons-logging-1.1.1.jar

JavaBean类:

package cn.zy.study;
/**
* 提供get和set方法
* 并有一个无参的构造方法
* @author zy
*
*/
public class Person { private String name;
private int age;
private String gender;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", gender=" + gender
+ "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
} }

  

对bean类的操作

package cn.test;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test; import cn.zy.study.Person; public class Demo3 { @Test
public void fun1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
//用Class类的forName方法来获取对应的class对象
String className = "cn.zy.study.Person";
Class clazz = Class.forName(className);
//使用clazz对应类的默认构造器创造实例
Object bean = clazz.newInstance();
/**使用beanutils工具设置bean类的属性值,
* 所有的属相值都可以设置成String类型,将会自动转换
* 没有设置属性的值将为null
*/
BeanUtils.setProperty(bean, "name", "Scott");
BeanUtils.setProperty(bean, "age", "17");
System.out.println(bean);
//得到bean类的属性值,注意属值都将变成String类型
String name = BeanUtils.getProperty(bean, "name");
String age = BeanUtils.getProperty(bean, "age"); } @Test
/**
* 将map直接封装到一个bean中
*/
public void fun2() throws InstantiationException, IllegalAccessException, InvocationTargetException{
Map<String,String> map = new HashMap();
map.put("name","Scott");
map.put("age","15");
//利用类的class属性来获取Class对象,并创建
Person bean = Person.class.newInstance();
//将map数据填充到Javabean中
BeanUtils.populate(bean, map);
System.out.println(bean);
} }

  

05-11 22:52