利用反射实现Map对象和Object对象之间相互转化

1.  Map ----> Object

    public static <T> T mapToBean(Map<String, Object> map, Class<T> obj) throws Exception {
        if (map == null) {
            return null;
        }
        Set<Entry<String, Object>> sets = map.entrySet();
        T t = obj.newInstance();
        Method[] methods = obj.getDeclaredMethods();
        for (Entry<String, Object> entry : sets) {
            String str = entry.getKey();
            String setMethod = "set" + str.substring(0, 1).toUpperCase() + str.substring(1);
            for (Method method : methods) {
                if (method.getName().equals(setMethod)) {
                    method.invoke(t, entry.getValue());
                }
            }
        }
        return t;
    }

2. Object --> Map

  方法一:

    public  Map<String,Object> objectToMap(Object obj) {
        Map<String,Object> map = new HashMap<String,Object>();
        Class<?> c = null;
        try {
            c = Class.forName(obj.getClass().getName());
            Method[] m = c.getMethods();
            for (int i = 0; i < m.length; i++) {
                String method = m[i].getName();
                if (method.startsWith("get") && !method.equals("getClass")) {
                    try {
                        Object value = m[i].invoke(obj);
                        if (value != null) {
                            String key = method.substring(3);
                            key = key.substring(0, 1).toLowerCase() + key.substring(1);
                            map.put(key, value);
                        }
                    } catch (Exception e) {
                        logger.error("出现错误");
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("出现错误");
            e.printStackTrace();
        }
        return map;
    }

 方法二:

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public static Map<String, Object> transBean2Map(Object obj) {  
        if(obj == null){  
            return null;  
        }          
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
                if (!key.equals("class")) {  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
                    map.put(key, value);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("transBean2Map Error " + e);  
        }  
        return map;  
    } 

猜你喜欢

转载自ihenu.iteye.com/blog/2265844
今日推荐