Map转化为Bean的方法

本文介绍了一个实用的Java工具类BeanUtil,该工具类提供了Bean对象与Map之间的相互转换方法,包括将Map转换为Bean、将Bean转换为Map等功能。BeanUtil通过反射机制实现了不同类型的数据转换,并能处理各种基本数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 数据结果集与对象之间的操作公共类
 * 
 * @author Administrator 2012-4-9
 */
public class BeanUtil {

	public BeanUtil() {
	}

	/**
	 * Map转换为Bean
	 * 
	 * @param pojo
	 * @param map
	 * @return
	 */
	public static <T> T buildBean(T pojo, Map<String, String> map) {

		Class classType = pojo.getClass();
		Iterator<String> it = map.keySet().iterator();
		try {
			// 遍历结果集数据列
			while (it.hasNext()) {
				// 获取列名 如Property
				String fieldName = it.next().toLowerCase();
				// 将列名第一个字母大写 P
				String stringLetter = fieldName.substring(0, 1).toUpperCase();

				// 通过属性名组成set()get()方法名符串setProperty getProperty
				String setName = "set" + stringLetter + fieldName.substring(1);
				String getName = "get" + stringLetter + fieldName.substring(1);

				// 通过方法名获取set/get方法
				// public return packageName.pojoName.getProperty()
				Method getMethod = classType.getMethod(getName, new Class[] {});
				// getMethod.getReturnType() 通过getProperty()方法获取返回类型
				Method setMethod = classType.getMethod(setName, new Class[] { getMethod.getReturnType() });

				// 通过setProperty()方法获取参数数据类型
				Class fieldType = setMethod.getParameterTypes()[0];
				// 判断数据类型并从结果集中获取数据
				Object value = formatValue(map, fieldType, fieldName);
				// 赋值操作 将value值射入pojo对象
				setMethod.invoke(pojo, new Object[] { value });
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

		return pojo;
	}

	/**
	 * 将map中数据与bean中属性类型一致
	 * 
	 * @param map
	 * @param fieldType
	 *            属性类型
	 * @param fieldName
	 *            属性名
	 * @return
	 */
	private static Object formatValue(Map<String, String> map, Class fieldType, String fieldName) {
		Object value = null;

		if (fieldType == Integer.class || "int".equals(fieldType.getName())) {
			if (map.get(fieldName) != null) {
				value = Integer.parseInt(map.get(fieldName));
			}
		} else if (fieldType == Float.class || "float".equals(fieldType.getName())) {
			if (map.get(fieldName) != null) {
				value = Float.parseFloat(map.get(fieldName));
			}
		} else if (fieldType == Double.class || "double".equals(fieldType.getName())) {
			if (map.get(fieldName) != null) {
				value = Double.parseDouble(map.get(fieldName));
			}
		} else if (fieldType == Date.class || fieldType == java.util.Date.class) {
			if (map.get(fieldName) != null) {
				value = Date.valueOf(map.get(fieldName));
			}
		} else {
			value = map.get(fieldName);
		}

		return value;
	}

	/**
	 * 将一个 Map 对象转化为一个 JavaBean
	 * 
	 * @param type
	 *            要转化的类型
	 * @param map
	 *            包含属性值的 map
	 * @return 转化出来的 JavaBean 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InstantiationException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */

	@SuppressWarnings("rawtypes")
	public static Object convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
		BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
		Object obj = type.newInstance(); // 创建 JavaBean 对象

		// 给 JavaBean 对象的属性赋值
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();

			if (map.containsKey(propertyName)) {
				// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值.
				Object value = map.get(propertyName);

				Object[] args = new Object[1];
				args[0] = value;

				descriptor.getWriteMethod().invoke(obj, args);
			}
		}
		return obj;
	}

	/**
	 * 将一个 JavaBean 对象转化为一个 Map
	 * 
	 * @param bean
	 *            要转化的JavaBean 对象
	 * @return 转化出来的 Map 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */

	@SuppressWarnings("rawtypes")
	public static Map convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map returnMap = new HashMap();
		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;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值