本文共 2033 字,大约阅读时间需要 6 分钟。
import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.beans.Transient;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;public class Tools { public static MapbeanToMap(Object obj) { try { 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(); Transient annotation = getter.getAnnotation(Transient.class); if (annotation == null) { Object value = getter != null ? getter.invoke(obj) : null; map.put(key, value); } } return map; } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage()); } }}
import org.apache.commons.beanutils.BeanUtils;private Map beanToMap(Object obj) { try { return BeanUtils.describe(obj); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return null;}private List mapToBean(List
转载地址:http://ovcsn.baihongyu.com/