JavaBean和Map相互转换

你的名字 2022-05-11 05:52 305阅读 0赞

Jdk bean转map

  1. import java.beans.BeanInfo;
  2. import java.beans.IntrospectionException;
  3. import java.beans.Introspector;
  4. import java.beans.PropertyDescriptor;
  5. import java.beans.Transient;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. public class Tools {
  11. public static Map<String, Object> beanToMap(Object obj) {
  12. try {
  13. Map<String, Object> map = new HashMap();
  14. BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  15. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  16. for (PropertyDescriptor property : propertyDescriptors) {
  17. String key = property.getName();
  18. if (key.compareToIgnoreCase("class") == 0) {
  19. continue;
  20. }
  21. Method getter = property.getReadMethod();
  22. Transient annotation = getter.getAnnotation(Transient.class);
  23. if (annotation == null) {
  24. Object value = getter != null ? getter.invoke(obj) : null;
  25. map.put(key, value);
  26. }
  27. }
  28. return map;
  29. } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
  30. throw new IllegalArgumentException(e.getMessage());
  31. }
  32. }
  33. }

apache bean和map互转

  1. import org.apache.commons.beanutils.BeanUtils;
  2. private Map beanToMap(Object obj) {
  3. try {
  4. return BeanUtils.describe(obj);
  5. } catch (IllegalAccessException | InvocationTargetException
  6. | NoSuchMethodException e) {
  7. e.printStackTrace();
  8. }
  9. return null;
  10. }
  11. private List<?> mapToBean(List<Map<String, Object>> data, Class<?> clazz) {
  12. List<Object> list = new ArrayList<>();
  13. try {
  14. for (int i = 0; i < data.size(); i++) {
  15. Object newInstance = clazz.newInstance();
  16. Map<String, Object> map = data.get(i);
  17. BeanUtils.populate(newInstance, map);
  18. list.add(newInstance);
  19. }
  20. return list;
  21. } catch (Exception e) {
  22. }
  23. return null;
  24. }

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读