一个很困惑的问题,希望大家简答一下。关于beanUtils的。
本帖最后由 fortheother 于 2013-08-15 16:22:53 编辑
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()
{
System.out.println("私有方法");
}
public Person(String name,int age ,Date birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}
public String run()
{
System.out.println("Person "+name+" run");
return "run";
}
public void eat()
{
System.out.println("Person "+name+"eat");
}
@Override
public String toString()
{
return "Person [age=" + age + ", name=" + name + ",birthday=" + birthday + "]";
}
/*public static void main(String[] args)
{
System.out.println("abc");
}*/
/*public Class[] getClass(String name,int[] password)
{
return new Class[]{String.class};
}
*/
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Date getBirthday()
{
return birthday;
}
public void setBirthday(Date birthday)
{
this.birthday = birthday;
}
}
[解决办法]
我用你代码试了下,好用的
开始测试.....
开始设置数据.....
名字设置成功....
年龄设置成功....
注册字符串转换为date类型转换器
生日设置成功....
打印数据........
Person [age=34, name=王佳佳,birthday=Tue Jan 15 00:00:00 CST 1985]
测试结束.........