import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Transform {
/**
* 字符串转日期
* @param str
* @return
*/
public static Date stringToDate(String str){
Date date = null;
try {
date = new SimpleDateFormat().parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* beanUtils格式转化器
*/
public static void beanUtilsConvert(){
//String -->date
DateConverter converter = new DateConverter();
converter.setPattern(new String("yyyy-MM-dd"));
ConvertUtils.register(converter,Date.class);
}
}
test
@Test
public void testBeanUtilsConvert() throws InvocationTargetException, IllegalAccessException {
Map<String,String> params = new HashMap<>();
People people = new People();
params.put("birthday","2020-10-09");
params.put("age","19");
Transform.beanUtilsConvert();
BeanUtils.populate(people,params);
System.out.println(people.toString());
//People{birthday=Fri Oct 09 00:00:00 CST 2020, age=19}
}
BeanUtils.populate的用法
BeanUtils位于org.apache.commons.beanutils.BeanUtils下面,其方法populate的作用解释如下:
完整方法:
BeanUtils.populate( Object bean, Map properties ),
这个方法会遍历map<key, value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。