Pojo2MapUtil.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.sooka.common.utils;
  2. import com.google.common.collect.Maps;
  3. import com.sooka.mybatis.model.TCmsContent;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.beans.BeanInfo;
  7. import java.beans.IntrospectionException;
  8. import java.beans.Introspector;
  9. import java.beans.PropertyDescriptor;
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.lang.reflect.Method;
  12. import java.util.Date;
  13. import java.util.Map;
  14. /**
  15. * Description:pojo 转 map
  16. *
  17. *
  18. * @create 2017-06-15
  19. **/
  20. public class Pojo2MapUtil {
  21. private static final Logger log = LoggerFactory.getLogger(Pojo2MapUtil.class);
  22. public static Map<String, ?> toMap(Object o) throws Exception {
  23. Map<String, Object> values = Maps.newHashMap();
  24. BeanInfo info = Introspector.getBeanInfo(o.getClass());
  25. log.debug(">>>>>>>>>> pojo to map [begin]");
  26. for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
  27. Method getter = pd.getReadMethod();
  28. if (getter != null) {
  29. log.debug(pd.getName() + "-->" + getter.invoke(o));
  30. values.put(pd.getName(), getter.invoke(o));
  31. }
  32. else {
  33. log.debug(">>>>>>>>>> null getter"+getter);
  34. }
  35. }
  36. log.debug(">>>>>>>>>> pojo to map [end]");
  37. return values;
  38. }
  39. public static <T> T toObj(Class<T> clazz, Map map)
  40. throws IntrospectionException, IllegalAccessException,
  41. InstantiationException, InvocationTargetException, ClassNotFoundException {
  42. T obj = clazz.newInstance();
  43. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  44. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  45. log.debug(">>>>>>>>>> map to pojo [begin]");
  46. for (int i = 0; i< propertyDescriptors.length; i++) {
  47. PropertyDescriptor descriptor = propertyDescriptors[i];
  48. String propertyName = descriptor.getName();
  49. if (map.containsKey(propertyName)) {
  50. Object value = map.get(propertyName);
  51. Object[] args = new Object[1];
  52. args[0] = value;
  53. descriptor.getWriteMethod().invoke(obj, args);
  54. log.debug(">>>>>>>>>> "+propertyName+ "==>" + map.get(propertyName));
  55. }
  56. }
  57. log.debug(">>>>>>>>>> map to pojo [end]");
  58. return obj;
  59. }
  60. public static void main(String[] args) throws Exception {
  61. TCmsContent content = new TCmsContent();
  62. content.setContentId(999999L);
  63. content.setModelId(11111);
  64. content.setUpdatedate(new Date());
  65. Map m = toMap(content);
  66. m.forEach((key,value)->
  67. System.out.println(key+"-->>"+value)
  68. );
  69. }
  70. }