Home  >  Article  >  Java  >  How to convert Java Bean and Map to each other? (code)

How to convert Java Bean and Map to each other? (code)

不言
不言forward
2018-10-08 15:09:101707browse

The content of this article is about how to convert Java Bean and Map to each other? (code), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Overview

Apache's BeanUtils Bean tool class is very powerful and basically covers all methods of Bean operations. Here we will talk about two aspects, one is Bean covert to Map, and the other is Map covert to Bean; Bean to Map actually uses Java's dynamic-Reflection technology. No matter what kind of Bean it is, it can be converted through dynamic parsing. It becomes a Map object, but the prerequisite is that the field must conform to camel case naming, which is also a coding specification. Another condition is that each field requires getter and setter methods. Map to Bean is also dynamically parsed into Bean through Reflection. Java's Reflection is actually very important. It exists in many tool classes we use. We not only need to be able to use it, but more importantly, we must be able to understand why. It is best to implement it by handwriting yourself. This will deepen our understanding.

Use Apache BeanUtils to convert Bean to Map

Code implementation

/**
     * 用apache的BeanUtils实现Bean covert to Map
     * @throws Exception
     */
    public static void beanToMap() throws Exception {
        User user=new User();
        Map<String,String> keyValues=null;

        user.setPassWord("password");
        user.setComments("test method!");
        user.setUserName("wang shisheng");
        user.setCreateTime(new Date());

        keyValues=BeanUtils.describe(user);

        LOGGER.info("bean covert to map:{}", JSONObject.toJSON(keyValues).toString());
    }

Test results

Use Apache BeanUtils to convert Map to Bean

Code implementation

/**
     * 用apache的BeanUtils实现Map covert to Bean
     * @throws Exception
     */
    public static void mapToBean() throws Exception {
        Map<String,String> keyValues=new HashMap<>();
        User user=new User();

        keyValues.put("sessionId","ED442323232ff3");
        keyValues.put("userName","wang shisheng");
        keyValues.put("passWord","xxxxx44333");
        keyValues.put("requestNums","34");

        BeanUtils.populate(user,keyValues);

        LOGGER.info("map covert to bean:{}", user.toString());
    }

Test results

##Understanding the implementation of BeanUtils converting Bean to Map and writing Bean to Map

Code implementation

/**
     * 应用反射(其实工具类底层一样用的反射技术)
     * 手动写一个 Bean covert to Map
     */
    public static void autoBeanToMap(){
        User user=new User();
        Map<String,Object> keyValues=new HashMap<>();
        user.setPassWord("password");
        user.setComments("test method!");
        user.setUserName("wang shisheng");
        user.setUserCode("2018998770");
        user.setCreateTime(new Date());
        Method[] methods=user.getClass().getMethods();
        try {
            for(Method method: methods){
                String methodName=method.getName();
                //反射获取属性与属性值的方法很多,以下是其一;也可以直接获得属性,不过获取的时候需要用过设置属性私有可见
                if (methodName.contains("get")){
                    //invoke 执行get方法获取属性值
                    Object value=method.invoke(user);
                    //根据setXXXX 通过以下算法取得属性名称
                    String key=methodName.substring(methodName.indexOf("get")+3);
                    Object temp=key.substring(0,1).toString().toLowerCase();
                    key=key.substring(1);
                    //最终得到属性名称
                    key=temp+key;
                    keyValues.put(key,value);
                }
            }
        }catch (Exception e){
            LOGGER.error("错误信息:",e);
        }
        LOGGER.info("auto bean covert to map:{}", JSONObject.toJSON(keyValues).toString());
    }

Test result

The above is the detailed content of How to convert Java Bean and Map to each other? (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete