Generate Map from POJO

前端 未结 2 2098
别那么骄傲
别那么骄傲 2021-02-04 15:34

I have a POJO, and a (currently not-yet-built) class that will return Lists of it. I\'d like to automatically generate the code necessary for the POJO to be accessed as a Map. I

2条回答
  •  不要未来只要你来
    2021-02-04 16:23

    You can use Commons BeanUtils BeanMap for this.

    Map map = new BeanMap(someBean);
    

    Update: since that's not an option due to some apparent library dependency problems in Android, here's a basic kickoff example how you could do it with little help of Reflection API:

    public static Map mapProperties(Object bean) throws Exception {
        Map properties = new HashMap<>();
        for (Method method : bean.getClass().getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers())
                && method.getParameterTypes().length == 0
                && method.getReturnType() != void.class
                && method.getName().matches("^(get|is).+")
            ) {
                String name = method.getName().replaceAll("^(get|is)", "");
                name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");
                Object value = method.invoke(bean);
                properties.put(name, value);
            }
        }
        return properties;
    }
    

    If java.beans API were available, then you could just do:

    public static Map mapProperties(Object bean) throws Exception {
        Map properties = new HashMap<>();
        for (PropertyDescriptor property : Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()) {
            String name = property.getName();
            Object value = property.getReadMethod().invoke(bean);
            properties.put(name, value);
        }
        return properties;
    }
    

提交回复
热议问题