beanutils.Converter使用案例

本文介绍如何使用Apache Commons BeanUtils库中的Converter接口实现自定义类型转换器,包括日期和数值类型的转换,并提供了一个具体的项目开发案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Converter主要是实现类型转功能。我们通常可以定义自己的Converter类。如:

import org.apache.commons.beanutils.Converter;    

public class DateConvert implements Converter{

public Object convert(Class arg0, Object arg1) {
String p = (String)arg1;
if(p== null || p.trim().length()==0){
return null;
}
try{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.parse(p.trim());
}
catch(Exception e){
return null;
}
}

}


自定义对象转换类的使用:

在使用之前先注册



ConvertUtils.register(new DateConvert(), java.util.Date.class);

因为要注册converter,所以不能再使用BeanUtils的静态方法了,必须创建BeanUtilsBean实例
BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils,new PropertyUtilsBean());
beanUtils.setProperty(bean, name, value);


项目开发案例:

/**
* 设置Struts 中数字<->字符串转换,字符串为空值时,数字默认为null,而不是0.
* 也可以在web.xml中设置struts的参数达到相同效果,在这里设置可以防止用户漏设web.xml.
*/
public static void registConverter() {
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
//ConvertUtils.register(new DateConverter("yyyy-MM-dd"), Date.class);
ConvertUtils.register(new DateConverter(null), Date.class);
ConvertUtils.register(new StringConverter(),String.class);
}



DateConverter:

import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* 简易DateConverter.
* 供Apache BeanUtils 做转换,默认时间格式为yyyy-MM-dd,可由构造函数改变.
*
* @author calvin
*/
public class DateConverter implements Converter {
private static final Log log = LogFactory.getLog(DateConverter.class);
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

public DateConverter(String formatPattern) {
if (StringUtils.isNotBlank(formatPattern)) {
format = new SimpleDateFormat(formatPattern);
}
}

public Object convert(Class arg0, Object value) {
try {
String dateStr = (String) value;

if (StringUtils.isNotBlank(dateStr)) {
return format.parse(dateStr);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值