java对象转化为Map

来源:互联网 发布:汉化软件安卓版下载 编辑:程序博客网 时间:2024/06/05 20:37
public Map<String, String> map2Bean(Object obj) {        if (obj == null) {            return null;        }        Map<String, String> map = new HashMap<String, String>();        try {            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();            for (PropertyDescriptor property : propertyDescriptors) {                String key = property.getName();                // 过滤class属性                if (!key.equals("class")) {                    // 得到property对应的getter方法                    Method getter = property.getReadMethod();                    Object object = getter.invoke(obj);                    if (object != null) {                        String value = object.toString();                        map.put(key, value);                    }                }            }        } catch (Exception e) {            System.out.println("transBean2Map Error " + e);        }        return map;    }
原创粉丝点击