Met today need to convert a function javabean attributes to map <String, String>, the thought of apache commons-beanutils of BeanUtils tools may have this function. It was found that there describe can be achieved. The next test can be converted, but found a problem, date type can not convert well, it can only be converted into Thu Sep 17 19:26:59 CST 2015 this format, and I need yyyy-MM-dd format. Turned down the source found a date converter DateConverter, try the next registered to BeanUtilsBean in.
BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
DateConverter converter = new DateConverter();
converter.setPattern("yyyy-MM-dd");
beanUtilsBean.getConvertUtils().register(new ConverterFacade(converter), java.util.Date.class);
But found ineffective, found to continue reading the source, it uses only StringConverter a converter code below.
public String convert(Object value) {
if (value == null) {
return null;
} else if (value.getClass().isArray()) {
if (Array.getLength(value) < 1) {
return (null);
}
value = Array.get(value, 0);
if (value == null) {
return null;
} else {
Converter converter = lookup(String.class);
return (converter.convert(String.class, value));
}
} else {
Converter converter = lookup(String.class);
return (converter.convert(String.class, value));
}
}
No option but to re-cover the code, the final code is as follows:
public class ExtConvertUtilsBean extends ConvertUtilsBean{
@Override
public String convert(Object value) {
if (value == null) {
return null;
} else if (value.getClass().isArray()) {
if (Array.getLength(value) < 1) {
return (null);
}
value = Array.get(value, 0);
if (value == null) {
return null;
} else {
Converter converter = lookup(String.class);
return (converter.convert(String.class, value));
}
} else {
Converter converter = null;
if(value instanceof java.util.Date ){
converter = lookup(java.util.Date.class);
}else{
converter = lookup(String.class);
}
return (converter.convert(String.class, value));
}
}
}
DateConverter converter = new DateConverter();
converter.setPattern(pattern);
beanUtilsBean.getConvertUtils().register(new ConverterFacade(converter), java.util.Date.class);
beanUtilsBean.describe(object);
At this point you can implement a custom date formatting functionality.