There are many ways to convert javabean and map, such as:
1. Convert bean to json through ObjectMapper, and then convert json to map. However, this method is complicated and inefficient. , after testing, it takes 12 seconds to convert 10,000 beans in a loop! ! ! It is not recommended to use
2. Obtain the attributes and values of the bean class through Java reflection, and then convert them into the key-value pairs corresponding to the map. This method is the second best, but it is a little troublesome
3. Through the method in the net.sf.cglib.beans.BeanMap class, this method is extremely efficient. The difference between it and the second method is that it uses cache. The bean needs to be initialized when it is first created, and then the cache is used. Therefore, it is extremely fast. After testing, it only takes about 300 milliseconds to loop through bean and map conversions 10,000 times.
So, the third method is recommended. The following is the relevant code:
/** * 将对象装换为map * @param bean * @return */ public static MapbeanToMap(T bean) { Map map = Maps.newHashMap(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { map.put(key+"", beanMap.get(key)); } } return map; } /** * 将map装换为javabean对象 * @param map * @param bean * @return */ public static T mapToBean(Map map,T bean) { BeanMap beanMap = BeanMap.create(bean); beanMap.putAll(map); return bean; } /** * 将List转换为List
The above is the detailed content of How to convert objects to Maps in Java - using BeanMap. For more information, please follow other related articles on the PHP Chinese website!