Java introspection: object to map

后端 未结 7 987
无人及你
无人及你 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:18

    Here's a rough approximation, hopefully enough to get you pointed in the right direction:

    public Map getMap(Object o) {
        Map result = new HashMap();
        Field[] declaredFields = o.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            result.put(field.getName(), field.get(o));
        }
        return result;
    }
    

提交回复
热议问题