java实体类转成Map


将实体类转成Map


	private static Logger LOGGER = LoggerFactory.getLogger(BeanUtils.class);

	// Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
	public static Map transBean2Map(Object obj) {
		if (obj == null) {
			return null;
		}
		Map map = new HashMap();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);

					map.put(key, value);
				}

			}
		} catch (Exception e) {
			LOGGER.error("transBean2Map Error {}" ,e);
		}
		return map;

	}


你可能感兴趣的:(JAVA)