Object 转Map

Object 转Map

/**
     * Object 转Map
     * @param obj
     * @return
     * @throws Exception
     */
    public Map objToMap(Object obj) throws Exception{
        Map map=new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter!=null ? getter.invoke(obj) : "";
            map.put(key, value);
        }
        return map;
    }

你可能感兴趣的:(java)