从POJO生成Map <String,String>

And*_*use 8 java android pojo listactivity

我有一个POJO和一个(当前尚未构建的)类,它将返回它的列表.我想自动生成POJO作为Map访问所需的代码.这是一个好主意,是否可以自动执行,我是否需要手动为每个我想要这样处理的POJO执行此操作?

谢谢,安迪

Bal*_*usC 16

你可以使用Commons BeanUtils BeanMap.

Map map = new BeanMap(someBean);
Run Code Online (Sandbox Code Playgroud)

更新:由于Android中存在一些明显的库依赖性问题,因此不是一个选项,这里有一个基本的启动示例,您可以在Reflection API的帮助下完成它:

public static Map<String, Object> mapProperties(Object bean) throws Exception {
    Map<String, Object> 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;
}
Run Code Online (Sandbox Code Playgroud)

如果java.beansAPI可用,那么您可以这样做:

public static Map<String, Object> mapProperties(Object bean) throws Exception {
    Map<String, Object> 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;
}
Run Code Online (Sandbox Code Playgroud)