java实体类转换为map

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* java实体类转换为map
* @author vic
*
*/

public class JavaBeanUtil {

  public static Map<String,Object> convertBeanToMap(Object bean) throws IntrospectionException,IllegalAccessException, InvocationTargetException {
  Class type = bean.getClass();
  Map<String,Object> returnMap = new HashMap<String, Object>();
  BeanInfo beanInfo = Introspector.getBeanInfo(type);
  PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  for (int i = 0; i < propertyDescriptors.length; i++) {
    PropertyDescriptor descriptor = propertyDescriptors[i];
    String propertyName = descriptor.getName();
    if (!propertyName.equals("class")) {
      Method readMethod = descriptor.getReadMethod();
      Object result = readMethod.invoke(bean, new Object[0]);
      if (result != null) {
        returnMap.put(propertyName, result);
      } else {
        returnMap.put(propertyName, "");
      }
    }
  }
    return returnMap;
  }

}

文末附上博主自己写的视频小网站,各种最新免费电影视频资源(搜索猴) www.sousuohou.com

电影公众号:https://m.veikee.cn/
原文地址:https://www.cnblogs.com/vicF/p/7461769.html