BeanUtils包的使用


19 System.out.println(st.getBirth());
20
21 }
复制代码

三、 自定义日期格式转换器

 

复制代码
1 @Test
2
3 public void test04()throws Exception{
4
5 //创建Student对象
6
7 Student st = new Student();
8
9 //使用CovertUtils注册创建一个日期格式转换器
10
11 ConvertUtils.register(new Converter() {
12
13
14
15 @Override
16
17 public Object convert(Class type, Object value) {
18
19 //当value参数等于空时返回空
20
21 if(value==null){
22
23 return null;
24
25 }
26
27 //自定义时间的格式为yyyy-MM-dd
28
29 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
30
31 //创建日期类对象
32
33 Date dt = null;
34
35
36
37 try {
38
39 //使用自定义日期的格式转化value参数为yyyy-MM-dd格式
40
41 dt = sdf.parse((String)value);
42
43 } catch (ParseException e) {
44
45 // TODO Auto-generated catch block
46
47 e.printStackTrace();
48
49 }
50
51 //返回dt日期对象
52
53 return dt;
54
55 }
56
57 }, Date.class);
58
59 //给birth赋值60 61 BeanUtils.setProperty(st, "birth", "1991-09-25");62 63 //输出64 65 System.out.println(st.getBirth());66 67 }
复制代码

ConvertUtils.register(new Converter()中,new Converter()就相当于重写了Converter类中方法:

       Public class MyConerter implements Converter{

              //并且在此处创建了匿名的对象

}

原文地址:https://www.cnblogs.com/jianmang/p/4735800.html