1、Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils
2、如何使用:
1)在src中新建一个文件夹lib
2)将commons-beanutils-1.8.0中的commons-beanutils-1.8.0放入lib中
3)将log4j中的commons-logging.jar放入
4)添加到path路径中
3、Beanutils工具包的常用类:
1)BeanUtils
2)PropertyUtils
3)ConvertUtils.regsiter(Converterconvert, Class clazz)
4)自定义转换器
代码说明:
//javabean 文件
//内省获取属性是通过方法获取
packagecom.hbsi.beanutils;
importjava.util.Date;
publicclass Person {
//如果没有set和get方法变量被称为字段,如果有被称为属性
privateString name;
privateintage;
private Date birthday;
public DategetBirthday() {
returnbirthday;
}
publicvoid setBirthday(Date birthday) {
this.birthday = birthday;
}
public StringgetName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
public String getAb()
{
returnnull;
}
}
//使用beanutils
packagecom.hbsi.beanutils;
importjava.lang.reflect.InvocationTargetException;
import java.text.*;
importjava.util.Date;
importorg.apache.commons.beanutils.*;
importorg.apache.commons.beanutils.locale.converters.DateLocaleConverter;
importorg.junit.Test;
publicclass Demo1 {
@Test
//通过操作为person的name赋值
publicvoid test1() throws IllegalAccessException,InvocationTargetException, NoSuchMethodException
{
Person p=new Person();
//获取属性
BeanUtils.getProperty(p,"name");
//设置属性底层调入了setName()方法
BeanUtils.setProperty(p,"name","张三");
System.out.println(p.getName());
}
//beanutils工具对基本数据类型可以自动转换
@Test
publicvoid test2() throws IllegalAccessException,InvocationTargetException
{
//如果有date类型,要自定义转换器(是接口),做一个匿名类
ConvertUtils.register(new Converter()
{
@Override
public Object convert(Class type, Objectvalue) {
//判读值是否存在
if(value==null)
{
returnnull;
}
//判断字串
if(!(value instanceof String))
{
thrownew ConversionException("只能转string数据");
}
//强转成字符串
String s=(String)value;
if(s.trim().equals(""))
{
returnnull;
}
//String转换成日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
Date d=sdf.parse(s);
return d;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
thrownew ConversionException("转换错误!");
}
}
},Date.class);
String name="张三";
String age="23";
String birthday="1992-01-01";
//保存到Person对象里
Person p=new Person();
BeanUtils.setProperty(p, "name", name);
BeanUtils.setProperty(p, "age", age);
BeanUtils.setProperty(p, "birthday",birthday);
System.out.println(p.getName()+" "+p.getAge()+" "+p.getBirthday().toLocaleString());
}
//使用beanutils中的转化器完成转换
publicvoid test3() throws IllegalAccessException,InvocationTargetException
{
ConvertUtils.register(new DateLocaleConverter(), Date.class);
Person p=new Person();
BeanUtils.setProperty(p,"birthday"," ");
//System.out.println(p.getBirthday());
}
}
/*class Myconver implements Converter
{
@Override
//实现抽象方法
public Object convert(Class arg0, Objectarg1) {
// TODO Auto-generated method stub
return null;
}
}*/