生成地图<字符串,字符串>从POJO [英] Generate Map<String,String> from POJO

查看:163
本文介绍了生成地图<字符串,字符串>从POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POJO,和(目前还未建)类,将返回它的列表。我想自动生成必要的POJO进行访问,地图上的code。这是一个好主意,是有可能自动做的,我需要手动为每一个POJO我想治疗这种方式做到这一点?

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. Is this a good idea, is it possible to do automatically, and do I need to do this manually for every POJO I want to treat this way?

谢谢, 刘德华

推荐答案

您可以使用共享的beanutils <一href="http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanMap.html"><$c$c>BeanMap对于这一点。

You can use Commons BeanUtils BeanMap for this.

Map map = new BeanMap(someBean);


更新:因为这不是一种选择,由于Android的一些明显的库相关问题,这里有一个基本的开球例如你怎么可以用的Reflection API


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<String, Object> mapProperties(Object bean) throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    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;
}

我不知道,如果<一个href="http://docs.oracle.com/javase/6/docs/api/java/beans/package-summary.html"><$c$c>java.beans API是在Android中使用,但如果是真的,那么你可以取代

I am not sure if java.beans API is available in Android, but if true, then you could replace

name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");

name = Introspector.decapitalize(name);

这篇关于生成地图&LT;字符串,字符串&GT;从POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆