心得21--JDK新特性5-Apache开发的内省API
1. Apache开发的内省方式
Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils
l Beanutils工具包的常用类:
• BeanUtils
• PropertyUtils
• ConvertUtils.regsiter(Converter convert, Class clazz)
• 自定义转换器
具体案例分析:
Javabean:Person
packagecom.java.Bean;
import java.util.Date;
publicclass Person {
private String name;
privateintage;
private Date birthday;
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
public Date getBirthday() {
returnbirthday;
}
publicvoid setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAbc() {
returnnull;
}
}
主要代码:
package com.java.Bean;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
importorg.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Test;
public class BeanUtil {
@Test //直接用的测试方法来调试程序
public voidtest1() throws IllegalAccessException, InvocationTargetException {
Person p =new Person();
BeanUtils.setProperty(p,"name","张三");
System.out.println(p.getName());
}
@Test
//beanutils工具对基本数据类型可以自动转换类型,但对Data等特殊类型的不能转换
public voidtest2() throws IllegalAccessException, InvocationTargetException {
Person p =new Person();
// 自定义的转换器中用到了匿名类,引用Convert是个借口,不能直接实例化它,但是想要用它的实例化对象,只能匿名类实他的方法,或者像以前那样创建一个类并实现该接口
ConvertUtils.register(newConverter() {
@Override
publicObject convert(Class type, Object value) {
if(value==null){
returnnull;
}
if(!(valueinstanceof String)) {
thrownew ConversionException("只能转换String类型!!!");
}
String s= (String)value;
/*if(s.trim().equals("")){
returnnull;
}*/
SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Dated = sdf.parse(s);
returnd;
} catch(ParseException e) {
thrownew ConversionException("转换错误!!!");
}
}
},Date.class);
String name ="李四";
String age ="21";
Stringbirthday = "1992-01-01 02:01:28";
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());
//这时会报错:org.apache.commons.beanutils.ConversionException:DateConverter does not support default String to 'Date' conversion.
//这时就需要自定义一个转换器
}
// BeanUtils给提供的转换类
@Test
public voidtest3() throws IllegalAccessException, InvocationTargetException {
ConvertUtils.register(newDateLocaleConverter(),Date.class);
Person p =new Person();
Stringbirthday = "1992-01-10"; // beanUtils自带的转换器有Bug,当你日期输入空值时则会出错,所以实际开发中常常用到自己定义的转换器。
BeanUtils.setProperty(p,"birthday",birthday);
System.out.println(p.getBirthday());
//实际开发中,像以上用到的String字符串都是web服务器客户端用户填写的表单
}
}