Java introspection: object to map

后端 未结 7 970
无人及你
无人及你 2020-11-28 05:52

I have a Java object obj that has attributes obj.attr1, obj.attr2 etc. The attributes are possibly accessed through an extra level of

7条回答
  •  一整个雨季
    2020-11-28 06:22

    You can use JavaBeans introspection for this. Read up on the java.beans.Introspector class:

    public static Map introspect(Object obj) throws Exception {
        Map result = new HashMap();
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            Method reader = pd.getReadMethod();
            if (reader != null)
                result.put(pd.getName(), reader.invoke(obj));
        }
        return result;
    }
    

    Big caveat: My code deals with getter methods only; it will not find naked fields. For fields, see highlycaffeinated's answer. :-) (You will probably want to combine the two approaches.)

提交回复
热议问题