一、前言
基于java.lang.reflect反向映射类对象映射工具类,实现了对象toMap方法转换java.util.Map、通过对象getProValue获取指定属性名称proName值、将Map转换为指定Class类对象mapToObj方法、通过对象属性映射getDeclaredFields转换getFieldsMap属性Map等方法处理。
二、代码示例
package test;@b@@b@import java.beans.BeanInfo;@b@import java.beans.Introspector;@b@import java.beans.PropertyDescriptor;@b@import java.lang.reflect.Field;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.math.BigDecimal;@b@import java.util.Date;@b@import java.util.HashMap;@b@import java.util.Iterator;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@@b@public class ObjectReflectUtils {@b@ @b@ public static class Student{@b@ @b@ private String name;@b@ private String classId;@b@ @b@ public Student() {@b@ super();@b@ }@b@@b@ public Student(String name, String classId) {@b@ super();@b@ this.name = name;@b@ this.classId = classId;@b@ }@b@ @b@ public String getName() {@b@ return name;@b@ }@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@ public String getClassId() {@b@ return classId;@b@ }@b@ public void setClassId(String classId) {@b@ this.classId = classId;@b@ }@b@@b@ @Override@b@ public String toString() {@b@ return "Student [getName()=" + getName() + ", getClassId()="@b@ + getClassId() + "]";@b@ }@b@ } @b@ @b@ private static void putValueToDTO(Object act, Map<String, Object> map, Method method) throws NoSuchMethodException,@b@ IllegalAccessException, InvocationTargetException {@b@ if (method.getName().startsWith("get")) {// 取出所有get方法@b@ String dtoMethodName = method.getName();@b@ if (null != dtoMethodName && 3 < dtoMethodName.length()) {@b@ Method getMethod = act.getClass().getMethod(dtoMethodName);@b@ Object getValue = getMethod.invoke(act);@b@ dtoMethodName = dtoMethodName.substring(3);@b@ dtoMethodName = dtoMethodName.substring(0, 1).toLowerCase() + dtoMethodName.substring(1);@b@ if (!"class".equals(dtoMethodName)) {@b@ map.put(dtoMethodName, getValue);@b@ }@b@ }@b@ }@b@ }@b@ @b@ @b@ public static Map getFieldsMap(Object obj) throws Exception{@b@ Field[] fields=obj.getClass().getDeclaredFields();@b@ Map fieldMap=new HashMap();@b@ for(Field f:fields){@b@ boolean accessible = f.isAccessible();@b@ if (!accessible) {@b@ f.setAccessible(true);@b@ }@b@ fieldMap.put(f.getName(),f.get(obj));@b@ }@b@ return fieldMap;@b@ }@b@ @b@ @b@ /**@b@ * 间对象属性转换为Map@b@ * @param obj 对象实例@b@ * @return 对象Map@b@ */@b@ public static Map<String, Object> toMap(Object obj) {@b@ if (obj == null) {@b@ return null;@b@ }@b@ try {@b@ Map<String, Object> map = new HashMap<String, Object>();@b@ Method[] methods = obj.getClass().getMethods();@b@ if (null == methods || 0 >= methods.length) {@b@ return null;@b@ }@b@ for (Method method : methods) {@b@ putValueToDTO(obj, map, method);@b@ }@b@ return map;@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ return null;@b@ }@b@ }@b@ @b@ /**@b@ * 通过属性名称获取其值@b@ * @param object@b@ * @param proName@b@ * @return@b@ * @throws Exception@b@ */@b@ public static Object getProValue(Object object,String proName)throws Exception{@b@ Method[] m = object.getClass().getMethods();@b@ for(int i = 0;i < m.length;i++){@b@ if(("get"+proName).toLowerCase().equals(m[i].getName().toLowerCase())){@b@ return m[i].invoke(object);@b@ }@b@ }@b@ return null;@b@ }@b@ @b@ // map转换成dto,名称同转大写,相同即写入@b@ public static Object mapToObj(Map map, Class cla) {@b@ if (cla == null) {@b@ return null;@b@ }@b@ Object obj = null;@b@ try {@b@// obj = Class.forName(cla.getClass().getName()).newInstance();@b@ obj = cla.newInstance();// 创建 JavaBean 对象@b@// obj =cla.getConstructors()[0].newInstance();@b@ } catch (Exception e1) {@b@ e1.printStackTrace();@b@ return null;@b@ }@b@ try {@b@ // 获取属性@b@ BeanInfo beanInfo = Introspector.getBeanInfo(cla);@b@ // 给 JavaBean 对象的属性赋值@b@ putValueToJavaBean(map, obj, beanInfo);@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ return obj;@b@ }@b@ @b@ @b@ /**@b@ * 判断Map中是否包含某个key值@b@ * @param map@b@ * @param cKey@b@ * @return@b@ */@b@ @SuppressWarnings({ "rawtypes", "unchecked" })@b@ private static Object isUpKeyContainsKeyToMap(Map map, String cKey) {@b@ if (map == null || map.isEmpty() || null == cKey) {@b@ return null;@b@ }@b@ Set set = map.entrySet();@b@ Iterator it = set.iterator();@b@ while (it.hasNext()) {@b@ Entry<String, String> entry = (Entry<String, String>) it.next();@b@ if (entry.getKey().replaceAll("_", "").equalsIgnoreCase(cKey.replaceAll("_", ""))) {@b@ return entry.getValue();@b@ }@b@ }@b@ return null;@b@ }@b@ @b@ /**@b@ * 将数值放到对象中@b@ * @param obj@b@ * @param descriptor@b@ * @param value@b@ * @throws IllegalAccessException@b@ * @throws InvocationTargetException@b@ */@b@ private static void putValueByBigDecimal(Object obj, PropertyDescriptor descriptor, Object value)@b@ throws IllegalAccessException, InvocationTargetException {@b@ BigDecimal bd = (BigDecimal) value;@b@ Object t = null;@b@ if ("Integer".equals(descriptor.getPropertyType().getSimpleName())) {@b@ t = bd.intValue();@b@ } else if ("Float".equals(descriptor.getPropertyType().getSimpleName())) {@b@ t = bd.floatValue();@b@ } else if ("Double".equals(descriptor.getPropertyType().getSimpleName())) {@b@ t = bd.doubleValue();@b@ }@b@ descriptor.getWriteMethod().invoke(obj, t);@b@ }@b@@b@@b@ /**@b@ * 将一个值放入javaBean中@b@ * @param map@b@ * @param obj@b@ * @param beanInfo@b@ */@b@ @SuppressWarnings("rawtypes")@b@ private static void putValueToJavaBean(Map map, Object obj, BeanInfo beanInfo) {@b@ PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();@b@ for (int i = 0; i < propertyDescriptors.length; i++) {@b@ PropertyDescriptor descriptor = propertyDescriptors[i];@b@ String propertyName = descriptor.getName();@b@ Object value = isUpKeyContainsKeyToMap(map, propertyName);@b@ if (null != value) {@b@ try {@b@ // 为空不用放@b@ if (null == value.getClass() || null == value.getClass().getSimpleName()) {@b@ continue;@b@ }@b@ // 根据类型放值进去@b@ if (value.getClass().getSimpleName().equals("BigDecimal")) {@b@ putValueByBigDecimal(obj, descriptor, value);@b@ } else if (value.getClass().getSimpleName().equals("Timestamp")) {@b@ descriptor.getWriteMethod().invoke(obj, (Date) value);@b@ } else if(value.getClass().getSimpleName().equals("Long")&&descriptor.getWriteMethod().getParameterTypes()[0].getSimpleName().equals("String")){@b@ descriptor.getWriteMethod().invoke(obj, value.toString());@b@ }else {@b@ // 进行赋值@b@ descriptor.getWriteMethod().invoke(obj, value);@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ }@b@ }@b@ @b@ @b@@b@ public static void main(String[] args) throws Exception{@b@ @b@ Student stu=new Student("小木人","c01");@b@ @b@ Map printMap=toMap(stu);@b@ @b@ System.out.println("toMap_01:"+printMap);@b@ @b@ System.out.println("getProValue_02:"+getProValue(stu,"name"));@b@ @b@ Student stu2=(Student)mapToObj(printMap,ObjectReflectUtils.Student.class);@b@ @b@ System.out.println("mapToOb3_02:"+stu2.toString());@b@ @b@ System.out.println("getFieldsMap_03:"+getFieldsMap(stu));@b@ @b@ }@b@@b@}
控制台结果
toMap_01:{classId=c01, name=小木人}@b@getProValue_02:小木人@b@mapToOb3_02:Student [getName()=小木人, getClassId()=c01]@b@getFieldsMap_03:{classId=c01, name=小木人}