java 使用反射轉換對象 Object to Map

來源:互聯網
上載者:User

Object to Map 轉換的三種方法


就是把對象以及其對應的屬性名稱 和屬性值, 映射到一個Map中


import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;/** * User: pengfei.hpf * Date: 14-5-8 * Time: 下午12:34 */public class ObjectToMap {    public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {        TestObject o = new TestObject();        o.setCity("beijing");        o.setName("bj");        o.setOrder("ASC");        ObjectToMap objectToMap = new ObjectToMap();        System.out.println("=========== Invoke objectToMapViaBeanInfo ===========");        objectToMap.objectToMapViaBeanInfo(o);        System.out.println("=========== Invoke objectToMapViaFields ===========");        objectToMap.objectToMapViaFields(o);        System.out.println("=========== Invoke objectToMapViaApacheTools ===========");        objectToMapViaApacheTools(o);    }    /**     * 通過Introspector 的方式複製屬性值     * */    private static void objectToMapViaBeanInfo(TestObject o) throws IntrospectionException, InvocationTargetException, IllegalAccessException {        Map<String, Object> result = new HashMap<String, Object>();        BeanInfo info = Introspector.getBeanInfo(o.getClass());        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {            Method reader = pd.getReadMethod();            //內容為null的過濾掉            if (reader == null || reader.invoke(o) == null) {                continue;            }           //預設繼承Object類的屬性,過濾掉            if (pd.getName().equalsIgnoreCase("class")) {                continue;            }            result.put(pd.getName(), reader.invoke(o));        }        for (String key : result.keySet()) {            System.out.println("Key:" + key + ";Value:" + result.get(key));        }    }    /**     * 通過getDeclaredFields 的方式複製屬性值     *  getDeclaredFields方式不會返回父類的屬性     * */    private static void objectToMapViaFields(TestObject o) throws IllegalAccessException {        Map<String, Object> resMap = new HashMap<String, Object>();        Field[] declaredFields = o.getClass().getDeclaredFields();        for (Field field : declaredFields) {            field.setAccessible(true);            //過濾內容為空白的            if (field.get(o) == null) {                continue;            }            resMap.put(field.getName(), field.get(o));        }        printOut(resMap);    }    /**     * 通過Apache beanUtils的方式複製屬性值     * 其內部實現方式同 方法1     * */    private static void objectToMapViaApacheTools(TestObject o) {        Map<String, Object> resMap = new org.apache.commons.beanutils.BeanMap(o);        printOut(resMap);    }    /**     * 列印結果     * */    private static void printOut(Map<String, Object> resMap) {        for (String key : resMap.keySet()) {            System.out.println("Key:" + key + ";Value:" + resMap.get(key));        }    }    /**     * 測試類別     * */    public static class TestObject {        String city;        String name;        String order;        public String getOrder() {            return order;        }        public void setOrder(String order) {            this.order = order;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;
        }        public String getCity() {            return city;        }        public void setCity(String city) {            this.city = city;        }    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.