日期:2014-05-18 浏览次数:20654 次
package cn.dzr.beanutils;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.junit.Test;
public class Demo
{
public static void main(String[] args)
{
}
@Test
public void test1() throws Exception, InvocationTargetException
{
System.out.println("开始测试.....");
ConvertUtils.register(new Converter()
{
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class arg0, Object arg1)
{
System.out.println("注册字符串转换为date类型转换器");
if(arg1 == null)
{
return null;
}
if(!(arg1 instanceof String))
{
throw new ConversionException("只支持字符串转换 !");
}
String str = (String)arg1;
if(str.trim().equals(""))
{
return null;
}
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
try{
return sd.parse(str);
}
catch(ParseException e)
{
throw new RuntimeException(e);
}
}
}, Date.class);
Person p = new Person();
String age = "34";
String name ="王佳佳";
String birthday = "1985-01-15";
System.out.println("开始设置数据.....");
BeanUtils.setProperty(p, "name", name);
System.out.println("名字设置成功....");
BeanUtils.setProperty(p, "age", age);
System.out.println("年龄设置成功....");
BeanUtils.setProperty(p, "birthday", birthday);
System.out.println("生日设置成功....");
System.out.println("打印数据........");
System.out.println(p);
System.out.println("测试结束.........");
}
}
package cn.dzr.beanutils;
import java.util.Date;
public class Person
{
int age;
String name;
public Date birthday;
public Person()
{
}
private void pMethod()