使用/BeanUtils操作javabean

 

public void test1()throws IlegallAccessException,InvocationTargetException{

Person p=new Person();

BeanUtils.setProperty(p,”name”,”xcc”);

Syste.out.println(p.getName());

}

使用BeanUutilsperson( javabean)的对象p name属性赋值为xcc;

public void test2()throws IlegallAccessException,InvocationTargetException{

String name=”aaaa”;

String password=”123”;

String age=”34”;

String birthday=”1980-09-09”;

ConvertUtils.register(new DatelocalConverter(),Date.class);

Prerson p=new Person();

BeaUtils.setProperty(p.”name”,name);

BeaUtils.setProperty(p,”password”,”password”);

BeaUtils.setProperty(p,”age”,”age”);

BeaUtils.setProperty(p,”birthday”,”birthday”);

}

BeanUtils只支持8种基本数据类型的自动转换;如果是要转换其它的需要转换器;

如上面要把date 类型的的转换成javabeanint 型的就注册了转换器;这里的转换器是jar包中带的;

 

下面是时间转换器的写法:

ConvertUtils.register(new Converter()

{

public Object convert(Class type,Object value){

if(value==null){

return null;

}

If(!(value instansof String)){

throw new ConversionException(“只支持String类型”)

}

String str=(String) value;

if(str.trim().equals(“”)){

return null;

}

SimpleDateFormat df=new SimpleDateFormat(“yyyy-MM-dd”);

try{

Return df.parse(str);

}catch(ParseException e){

e.printStackTrace();

}

}

},Date.class);

使用Map集合填充bean的属性:

public void test4()throws IlegallAccessException,InvocationTargetException{

Map map=new HashMap();

 

map.put( “name”,”aaaa”);

map.put(“password’,”123”);

map.put(age,”34”);

map.put( birthday,”1980-09-09”);

ConvertUtils.register(new DatelocalConverter(),Date.class);

Prerson bean=new Person();

BeaUtils.populatey(bean,map);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值