zoukankan      html  css  js  c++  java
  • CommonUtils

    CommonUtils类就两个方法:

    l、String uuid():生成长度32的随机字符,通常用来做实体类的ID。底层使用了UUID类完成;

    2、T toBean(Map, Class<T>):把Map转换成指定类型的Bean对象。通常用来获取表单数据(request.getParameterMap())封装到JavaBean中,底层使用了common-beanutils。

    注意,本方法要求map中键的名称要与Bean的属性名称相同才能完成映射,否则不能完成映射。

    package cn.edu.zk.sxx.test;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.junit.Test;
    
    import cn.itcast.commons.CommonUtils;
    
    public class CommonUtilsTest {
        /**
         * 测试CommonUtils类
         * 返回一个随机的32长的字符串
         * 
         * CommonUtils类依赖的jar:commons-beanutils.jar、commons-logging.jar
         */
        @Test
        public void testUuid(){
            String s = CommonUtils.uuid();
            System.out.println(s);
        }
        /**
         * 
         */
        @Test
        public void testToBean(){
            /*
             * 1、创建Map
             */
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("pid", "1");
            map.put("pname", "小小");
            map.put("age", "18");
            map.put("xxx", "XXX");
            //通过map的数据来创建person类型的Javabean对象
            Person p = CommonUtils.toBean(map, Person.class);
            System.out.print(p);
        }
        
    }

    person类

    注意:

    如果
          map的key:pid、pname、age、xxx
          person的属性:pid、pname、age、sex
          map中没有名为sex的键值,而多出一个名为xxx的键值,所以映射后的person对象的sex属性值为null。
          map中的age是字符串类型,而person的age是int类型,但toBean()方法会自动对Map中值进行类型转换。
        

    package cn.edu.zk.sxx.test;
    
    public class Person {
        private String pid;
        private String pname;
        private int age;
        public String getPid() {
            return pid;
        }
        public void setPid(String pid) {
            this.pid = pid;
        }
        public String getPname() {
            return pname;
        }
        public void setPname(String pname) {
            this.pname = pname;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "Person [pid=" + pid + ", pname=" + pname + ", age=" + age + "]";
        }
        
    }

    输出结果:

    1494321730(1)

  • 相关阅读:
    关于程序员认知和编程学习,没有任何一篇文章会讲得如此透彻
    Found 1 slaves: Use of uninitialized value in printf at /usr/local/percona-toolkit/bin/pt-online-schema-change line 8489
    alert 多语言的处理
    #!/bin/sh & #!/bin/bash区别
    mysql 常用
    java.io.FileNotFoundException
    struts1 & jquery form 文件异步上传
    简单的数据库连接池实例(java语言)
    null id in com.rocky.** entry 错误处理
    java unsupported major.minor version 51.0 解决
  • 原文地址:https://www.cnblogs.com/suxiaoxia/p/6831621.html
Copyright © 2011-2022 走看看