BeanUtils操作
1. BeanUtils的使用:
2. //通过beanutils赋值
3. @Test
4. publicvoid test() throws Exception {
5. //加载类
6. Class cla = Class.forName("com.csdn.java05.Student");
7. //实力bean对象
8. Student bean = (Student) cla.newInstance();
9. //通过beanutils赋值bena中name变量
10.BeanUtils.setProperty(bean, "name", "asd");
11.System.out.println(bean.getName());
12.}
13.//beanutils赋值有自动转换功能
14.@Test
15.publicvoid test1() throws Exception {
16.Class cla = Class.forName("com.csdn.java05.Student");
17.Student bean = (Student) cla.newInstance();
18.BeanUtils.setProperty(bean, "age","12");
19.System.out.println(bean.getAge());
20.}
21.//beanutils赋值给date类型的变量通过ConvertUtils.register()方法
22.@Test
23.publicvoid test2() throws Exception {
24.Class cla = Class.forName("com.csdn.java05.Student");
25.Student bean = (Student) cla.newInstance();
26.ConvertUtils.register(new DateLocaleConverter(), Date.class);
27.BeanUtils.setProperty(bean, "time","1992-12-12");
28.System.out.println(bean.getTime());
29.}
30.//beanutils赋值给date类型的变量通过自定义转换
31.@Test
32.publicvoid test3() throws Exception {
33.Class cla = Class.forName("com.csdn.java05.Student");
34.Student bean = (Student) cla.newInstance();
35.ConvertUtils.register(new Converter() {
36.public Object convert(Class type, Object arg1) {
37.if(arg1==null){
38.returnnull;
39.}
40.SimpleDateFormat si=new SimpleDateFormat("yyyy-MM-dd");
41.Date dt=null;
42.try {
43.dt=si.parse((String) arg1);
44.} catch (ParseException e) {
45.e.printStackTrace();
46.}
47.return dt;
48.}
49.}, Date.class);
50.BeanUtils.setProperty(bean, "time","1992-22-12");
51.System.out.println(bean.getTime());
52.}
53.在这当中如果用自定义的格式转换日期格式如果日期不符也会转换,但是通过ConvertUtils.register()错误的日期不会转换。在使用beanUtils需要导入jar包