精华内容
下载资源
问答
  • JavaObject转Map类型,Map转Object类型

    千次阅读 2020-07-31 09:40:11
    在使用Java编程过程中,经常会遇到获取的数据为Object类型,但只是以这种方式传输,实质还是Map类型,此时就涉及到两种类型的相互转换。 强制转换 在类型转换工程中,常见的转换方式为强制转换。如(String)map.get...

    前言

    在使用Java编程过程中,经常会遇到获取的数据为Object类型,但只是以这种方式传输,实质还是Map类型,此时就涉及到两种类型的相互转换。

    强制转换

    在类型转换工程中,常见的转换方式为强制转换。如(String)map.get(key),(int)map.get(key)等。但是如果接收的类型为Map,此时强转(Map<String, Object>) obj则会报出警告。

    治标不治本

    很多人会使用@SuppressWarnings(“unchecked”)来解决编辑器中的警告,好看是好看了。但是这用来告诉编译器忽略警告,而警告却实实在在的存在。项目的风险还是存在。

    方法一

    可以使用java.lang.reflect.Field类完成ObjMap之间的相互转换.

    • ObjectMap类型
    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String keyName = field.getName();
            Object value = field.get(obj);
            if (value == null)
                value = "";
            map.put(keyName, value);
        }
        return map;
    }
    
    • MapObject类型
    //Map转Object
    public static Object getMapToObject(Map<Object, Object> map, Class<?> cla) throws Exception {
        if (map == null)
            return null;
        Object obj = cla.newInstance();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            if (map.containsKey(field.getName())) {
                field.set(obj, map.get(field.getName()));
            }
        }
        return obj;
    }
    

    通过Field类进行数据类型的转换。

    方法二

    通过BeanUtils工具类进行转换

    //1、map转换为object
    
    public static Object mapToObject(Map<String, Object> map, Class<?> cla)
        throws Exception {
    	if (map == null) 
    		return null;
      Object obj = clas.newInstance();
    	org.apache.commons.beanutils.BeanUtils.populate(obj, map);
    	return obj;
    }
    
    //2、object转换为map
    public static Map<?, ?> objectToMap(Object obj) {
    	if (obj == null) 
    		return null;
    	return new org.apache.commons.beanutils.BeanMap(obj);
    }
    

    总结

    最后,通过调用这两个方法就可以实现Object转Map类型,Map转Object类型。

    展开全文
  • java Object转Map

    2016-06-20 17:37:00
     项目中,最近有这种需求,然后自己根据API提供的类,写了两个Object转Map的方法: /** * 使用java.beans.Introspector转换 * @param object * @return map * @throws Exception */ public static ...

     项目中,最近有这种需求,然后自己根据API提供的类,写了两个Object转Map的方法:

    /**
    	 * 使用java.beans.Introspector转换
    	 * @param object
    	 * @return map
    	 * @throws Exception
    	 */
    	public static Map<String, Object> obj2Map(Object object){
    		Map<String, Object> map = new HashMap<String, Object>();
    		// 获取Object对象
    		BeanInfo beanInfo = null;
    		try {
    			beanInfo = Introspector.getBeanInfo(object.getClass());
    		} catch (IntrospectionException e) {
    			e.printStackTrace();
    		}
    		// 获取Object属性描述
    		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    
    		for (PropertyDescriptor property : propertyDescriptors) {
    			String key = property.getName(); //获取属性名
    			if (key.compareToIgnoreCase("class") == 0) {
    				continue;
    			}
    			Method getter = property.getReadMethod();
    			Object value = null;
    			try {
    				value = getter != null ? getter.invoke(object) : null;//获取值
    				map.put(key, value);
    			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    				e.printStackTrace();
    			} 
    		}
    		return map;
    	}
    	
    
    	/**
    	 *  
    	 * 使用java.lang.reflect进行转换 
    	 * @param object
    	 * @return map
    	 */
        public static Map<String, Object> objToMap(Object object){
        	Map<String, Object> map = new HashMap<String, Object>();
        	try{
        		Field[] declaredFields = object.getClass().getDeclaredFields(); 
        		for (Field field : declaredFields) {    
                    field.setAccessible(true);  
                    try {
    					map.put(field.getName(), field.get(object));
    				} catch (IllegalArgumentException | IllegalAccessException e) {
    					e.printStackTrace();
    				}  
                } 
        	}catch(SecurityException e){
        		e.printStackTrace();
        	}
        	return map;
        }

    新建一个对象测试下:

    public class Test {
    
    	private String sex;
    	private String name;
    	
    	public Test(){
    		
    	}
    	
    	public Test(String sex,String name){
    		this.sex = sex;
    		this.name = name;
    	}
    	
    	public String getSex() {
    		return sex;
    	}
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Override
    	public String toString() {
    		return "Test [sex=" + sex + ", name=" + name + "]";
    	}
    	
    	
    }

    结果截图:

    173728_LaTD_563338.png

    173734_BSeN_563338.png

     

     

    转载于:https://my.oschina.net/zhengweishan/blog/697942

    展开全文
  • Map转换ObjectObject转换Map、List<Object>转换List<Map>、List<Map>转换List<Object>、对象拷贝

    Map转换Object、Object转换Map、List<Object>转换List<Map>、List<Map>转换List<Object>、对象拷贝

    package cn.framework.util;

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.math.BigDecimal;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;


    import javax.servlet.http.HttpServletRequest;


    /**
     * 对象类高级操作
     * 
     * @author jonas
     * 
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public class ObjectUtil {


    /**
    * 两个相同类型对象覆盖(oldObj覆盖newObj,isNullReplace当oldObj字段值为空是否覆盖,true覆盖,false不覆盖)

    * @author jonas
    * @date 2014-11-28 上午10:28:54
    * @param newObj
    * @param oldObj
    * @param isNullReplace
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    * @throws InvocationTargetException
    */
    public static void objectReplace(Object newObj, Object oldObj, boolean isNullReplace) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (newObj != null && oldObj != null) {
    Class _class1 = newObj.getClass();
    Class _class2 = oldObj.getClass();
    Field[] fields = _class1.getDeclaredFields();
    for (Field field : fields) {
    Method getMethod = getMethod(_class2, field, "get");
    if (getMethod != null) {
    Object value = getMethod.invoke(oldObj, null);
    if (!isNullReplace && value == null) {
    continue;
    }
    Method setMethod = getMethod(_class1, field, "set");
    setMethod.invoke(newObj, value);
    }
    }
    }
    }


    /**
    * 两个相同类型对象覆盖(oldObj覆盖newObj,isNullReplaceList里面值为空也需要覆盖的字段)

    * @author jonas
    * @date 2014-11-28 上午10:28:54
    * @param newObj
    * @param oldObj
    * @param isNullReplace
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    * @throws InvocationTargetException
    */
    public static void objectReplace(Object newObj, Object oldObj, List<String> isNullReplaceList)
    throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (newObj != null && oldObj != null) {
    if (isNullReplaceList == null) {
    isNullReplaceList = new ArrayList<String>();
    }
    Class _class1 = newObj.getClass();
    Class _class2 = oldObj.getClass();
    if (_class1.getName().equals(_class2.getName())) {
    Field[] fields = _class1.getDeclaredFields();
    for (Field field : fields) {
    Method getMethod = getMethod(_class1, field, "get");
    if (getMethod != null) {
    Object value = getMethod.invoke(oldObj, null);
    if (!isNullReplaceList.contains(field.getName()) && value == null) {
    continue;
    }
    Method setMethod = getMethod(_class1, field, "set");
    setMethod.invoke(newObj, value);
    }
    }
    }
    }
    }


    /**
    * 将List<T>里面对象转换成List<Map>

    * @author jonas
    * @date 2014-11-28 上午10:30:17
    * @param list
    * @return
    * @throws IllegalArgumentException
    * @throws IllegalAccessException
    * @throws ParseException
    * @throws InvocationTargetException
    */
    public static List<Map<String, Object>> listToMap(List list) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    List<Map<String, Object>> listMap = null;
    for (Object object : list) {
    if (listMap == null) {
    listMap = new ArrayList<Map<String, Object>>();
    }
    Map<String, Object> map = objectToMap(object, null);
    if (map != null && !map.isEmpty()) {
    listMap.add(map);
    }
    }
    return listMap;
    }


    public static Map<String, Object> objectToMap(Object object) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    Class _class = object.getClass();
    Field[] fields = _class.getDeclaredFields();
    Map<String, Object> map = null;
    for (Field field : fields) {
    if (map == null) {
    map = new HashMap<String, Object>();
    }
    Method method = getMethod(_class, field, "get");
    if (method != null) {
    setFieldValue(object, field, map, method, true);
    }
    }
    return map;
    }


    public static void listMapValueToString(List<Map> listMap) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    if (listMap == null) {
    return;
    }
    for (Map map : listMap) {
    mapValueToString(map);
    }
    }


    public static void listMapValueToStrings(List<Map<String, Object>> listMap) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    if (listMap == null) {
    return;
    }
    for (Map map : listMap) {
    mapValueToString(map);
    }
    }


    public static Map<String, Object> objectToMap(Object object, List<String> ignoreFieldList) {
    Class _class = object.getClass();
    Field[] fields = _class.getDeclaredFields();
    Map<String, Object> map = null;
    for (Field field : fields) {
    if (map == null) {
    map = new HashMap<String, Object>();
    }
    String fieldName = field.getName();
    if (ignoreFieldList != null && ignoreFieldList.contains(fieldName)) {
    continue;
    }
    Method method = getMethod(_class, fieldName, "get");
    if (method != null) {
    try {
    setFieldValue(object, field, map, method, true);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    return map;
    }


    /**
    * 将List<T>里面对象转换成List<Map>

    * @author jonas
    * @date 2014-11-28 上午10:30:17
    * @param list
    * @return
    * @throws IllegalArgumentException
    * @throws IllegalAccessException
    * @throws ParseException
    * @throws InvocationTargetException
    */
    public static List<Map<String, Object>> listToMap(List list, List<String> ignoreFieldList)
    throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    List<Map<String, Object>> listMap = null;
    for (Object object : list) {
    if (listMap == null) {
    listMap = new ArrayList<Map<String, Object>>();
    }
    Map<String, Object> map = objectToMap(object, ignoreFieldList);
    if (map != null && !map.isEmpty()) {
    listMap.add(map);
    }
    }
    return listMap;
    }


    public static void mapValueToString(Map map) {
    if (map != null) {
    for (Object key : map.keySet()) {
    Object value = map.get(key);
    if (value != null) {
    map.put(key, value.toString());
    }
    }
    }
    }


    public static List<Map> listToMapByMethod(List list) throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    List<Map> listMap = null;
    for (Object object : list) {
    if (listMap == null) {
    listMap = new ArrayList<Map>();
    }
    Map map = objectToMapByMethod(object, null);
    if (map != null && !map.isEmpty()) {
    listMap.add(map);
    }
    }
    return listMap;
    }


    public static List<Map<String, Object>> listToMapByMethod(List list, List<String> ignoreFieldList)
    throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    List<Map<String, Object>> listMap = null;
    for (Object object : list) {
    if (listMap == null) {
    listMap = new ArrayList<Map<String, Object>>();
    }
    Map<String, Object> map = objectToMapByMethod(object, ignoreFieldList);
    if (map != null && !map.isEmpty()) {
    listMap.add(map);
    }
    }
    return listMap;
    }


    public static Map<String, Object> objectToMapByMethod(Object object, List<String> ignoreFieldList)
    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException, SecurityException {
    Class _class = object.getClass();
    Method[] methods = _class.getMethods();
    Map map = null;
    for (Method method : methods) {
    if (map == null) {
    map = new HashMap();
    }
    String methodName = method.getName();
    if (ignoreFieldList != null && ignoreFieldList.contains(methodName)) {
    continue;
    }
    String prefix = methodName.substring(0, 3);
    String suffix = methodName.substring(3, methodName.length());
    if ("get".equals(prefix)) {
    setFieldValue(object, suffix, map, method, true);
    } else if ("set".equals(prefix)) {
    Method _method = null;
    try {
    _method = _class.getMethod("get" + suffix, null);
    } catch (NoSuchMethodException e) {
    }
    if (_method != null) {
    setFieldValue(object, suffix, map, _method, true);
    }
    } else {
    setFieldValue(object, methodName, map, method, true);
    }
    }
    return map;
    }


    /**
    * 将对象里面的String字段值消除空格

    * @author jonas
    * @date 2014-11-28 上午10:32:54
    * @param object
    * @return
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    * @throws InvocationTargetException
    * @throws ParseException
    */
    public static Object objectFieldTrim(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ParseException {
    Class _class = object.getClass();
    Field[] fields = _class.getDeclaredFields();
    for (Field field : fields) {
    Method method = getMethod(_class, field, "get");
    Object value = method.invoke(object, null);
    if (value != null) {
    if (field.getType().getName().equals("java.lang.String")) {
    setFieldValue(object, field, value.toString().trim());
    } else {
    setFieldValue(object, field, value.toString());
    }
    }
    }
    return object;
    }


    /**
    * 获取对象get或者set方法

    * @author jonas
    * @date 2014-11-28 上午10:34:56
    * @param _class
    * @param field
    * @param prefix
    * @return
    */
    public static Method getMethod(Class _class, Field field, String prefix) {
    Method[] methods = _class.getDeclaredMethods();
    for (Method method : methods) {
    String methodName = method.getName();
    String fieldName = field.getName();
    String _fieldName = prefix + fieldName;
    if (methodName.toUpperCase().equals(_fieldName.toUpperCase())) {
    return method;
    }
    }
    return null;
    }


    /**
    * 获取对象get或者set方法

    * @author jonas
    * @date 2014-11-28 上午10:34:56
    * @param _class
    * @param field
    * @param prefix
    * @return
    */
    public static Method getMethod(Class _class, String fieldName, String prefix) {
    Method[] methods = _class.getDeclaredMethods();
    for (Method method : methods) {
    String methodName = method.getName();
    String _fieldName = prefix + fieldName;
    if (methodName.toUpperCase().equals(_fieldName.toUpperCase())) {
    return method;
    }
    }
    return null;
    }


    private static void setFieldValue(Object obj, Field field, String value) throws IllegalArgumentException, IllegalAccessException, ParseException {
    field.setAccessible(true);
    String fieldType = field.getType().getName();
    if (fieldType.equals("java.lang.String")) {
    field.set(obj, value);
    } else if (fieldType.equals("java.lang.Integer") || fieldType.equals("int")) {
    field.set(obj, Integer.valueOf(value));
    } else if (fieldType.equals("java.lang.Long") || fieldType.equals("long")) {
    field.set(obj, Long.valueOf(value));
    } else if (fieldType.equals("java.lang.Float") || fieldType.equals("float")) {
    field.set(obj, Float.valueOf(value));
    } else if (fieldType.equals("java.lang.Double") || fieldType.equals("double")) {
    field.set(obj, Double.valueOf(value));
    } else if (fieldType.equals("java.util.Date")) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    field.set(obj, df.parse(value));
    } else if (fieldType.equals("java.math.BigDecimal")) {
    field.set(obj, new BigDecimal(value));
    } else if (fieldType.equals("java.lang.Boolean") || fieldType.equals("boolean")) {
    field.set(obj, Boolean.valueOf(value));
    } else if (fieldType.equals("java.lang.Byte") || fieldType.equals("byte")) {
    field.set(obj, Byte.valueOf(value));
    } else if (fieldType.equals("java.lang.Short") || fieldType.equals("short")) {
    field.set(obj, Short.valueOf(value));
    }
    }


    private static void setFieldValue(Object obj, Field field, Map map, Method method, boolean isLegalMethod)
    throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    field.setAccessible(true);
    String fieldName = field.getName();
    setFieldValue(obj, fieldName, map, method, isLegalMethod);
    }


    private static void setFieldValue(Object obj, String fieldName, Map map, Method method, boolean isLegalMethod)
    throws IllegalArgumentException, IllegalAccessException, ParseException, InvocationTargetException {
    if (map != null && map.containsKey(fieldName.toUpperCase())) {
    fieldName = obj.getClass().getSimpleName() + fieldName;
    }
    Class[] _c = method.getParameterTypes();
    Class returnCls = method.getReturnType();
    if (isLegalMethod) {
    if ((_c == null || _c.length == 0) && isBasicType(returnCls.getName())) {
    map.put(fieldName.toUpperCase(), method.invoke(obj, null));
    }
    } else {
    map.put(fieldName.toUpperCase(), method.invoke(obj, null));
    }
    }


    public static boolean isBasicType(String typeName) {
    if (typeName.equals("java.lang.String") || typeName.equals("java.lang.Integer") || typeName.equals("int") || typeName.equals("java.lang.Long") || typeName.equals("long")
    || typeName.equals("java.lang.Float") || typeName.equals("float") || typeName.equals("java.lang.Double") || typeName.equals("double")
    || typeName.equals("java.util.Date") || typeName.equals("java.math.BigDecimal") || typeName.equals("java.lang.Boolean") || typeName.equals("boolean")
    || typeName.equals("java.lang.Byte") || typeName.equals("byte") || typeName.equals("java.lang.Short") || typeName.equals("short")) {
    return true;
    } else {
    return false;
    }
    }


    public static boolean isCollectionType(Object obj) {
    if (obj instanceof Map || obj instanceof Collection) {
    return true;
    } else {
    return false;
    }
    }


    public static void loopFieldNewInstance(Object obj) throws Exception {
    Class cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
    Class fieldType = field.getType();
    if (!ObjectUtil.isBasicType(fieldType.getName()) && !fieldType.isInterface() && !ObjectUtil.isCollectionType(fieldType.newInstance())) {// 判断该字段是否基本类型
    Object _obj = fieldType.newInstance();
    Method method = ObjectUtil.getMethod(cls, field, "set");
    if (method != null) {
    method.invoke(obj, _obj);
    loopFieldNewInstance(_obj);
    }
    }
    }


    }


    public static void getPropertyStringByValue(Object obj, String prefix, List<String> propertyNames, List<Object> values) throws Exception {
    Class cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
    Method method = getMethod(cls, field, "get");
    Object value = null;
    if (method != null) {
    value = method.invoke(obj, null);
    }
    if (value != null) {
    String fieldType = field.getType().getName();
    String fieldName = (prefix == null ? "" : prefix + ".") + field.getName();
    if (isBasicType(fieldType)) {// 判断该字段是否基本类型
    propertyNames.add(fieldName);
    values.add(value);
    } else {
    boolean isColl = isCollectionType(field.getType().newInstance());
    if (!isColl) {// 不是集合类型
    getPropertyStringByValue(value, fieldName, propertyNames, values);
    }
    }
    }
    }


    }


    public static Object toObjectByRequest(Class cls, HttpServletRequest request) {
    try {
    Object object = cls.newInstance();
    Map map = request.getParameterMap();
    for (Iterator localIterator = map.keySet().iterator(); localIterator.hasNext();) {
    Object key = localIterator.next();
    String _key = key.toString();
    String value = request.getParameter(_key);
    if ((value != null) && (value.trim() != "")) {
    loopSetFieldValue(_key, object, value);
    }
    }
    return object;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }


    private static void loopSetFieldValue(String key, Object obj, String value) throws Exception {
    if (key.indexOf(".") == -1) {
    Field field = getFieldObj(obj, key);
    if (field != null) {
    setFieldValue(obj, field, value.toString());
    }
    } else {
    String prefix = key.substring(0, key.indexOf("."));
    String suffix = key.substring(key.indexOf(".") + 1, key.length());
    Field field = getFieldObj(obj, prefix);
    if (field != null) {
    Method getMethod = getMethod(obj.getClass(), field.getName(), "get");
    if (getMethod != null) {
    Object object = getMethod.invoke(obj, null);
    if (object == null) {
    object = field.getType().newInstance();
    Method setMethod = getMethod(obj.getClass(), field.getName(), "set");
    setMethod.invoke(obj, new Object[] { object });
    }
    if (suffix.indexOf(".") != -1) {
    loopSetFieldValue(suffix, object, value);
    } else {
    Field _field = getFieldObj(object, suffix);
    if (_field != null)
    setFieldValue(object, _field, value);
    }
    }
    }
    }
    }


    private static Field getFieldObj(Object object, String key) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
    Field field = fields[i];
    if (field.getName().equals(key)) {
    return field;
    }
    }
    return null;
    }

    }


    package cn.framework.util;


    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.math.BigDecimal;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;


    import javax.xml.datatype.DatatypeFactory;
    import javax.xml.datatype.XMLGregorianCalendar;


    import org.apache.commons.collections.MapUtils;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.BeanUtils;


    public class BaseCopyUtils extends BeanUtils {
    /**
    * JAVA 对象拷贝

    * @param source
    *            被拷贝的对象
    * @param target
    *            拷贝的新对象
    */
    public static void CopyObject(Object source, Object target) {
    if (source == null || target == null) {
    return;
    }
    BeanUtils.copyProperties(source, target);
    }

    public static void copyMap(Map<String,String> source, Map target) {
    if (source == null || source.isEmpty()) {
    return;
    }
    if (target == null) {
    target = new HashMap();
    }
    for (Map.Entry<String, String> entry : source.entrySet()) {
    target.put(entry.getKey(), entry.getValue());
    }
    }


    /**
    * @author nc 把Java对象转换为Map对象
    * @DATE (2015-3-9)
    * @param obj
    * @return
    */
    public static Map getMapByClass(Object obj) {
    Map map = new HashMap();
    try {
    Class cls = obj.getClass();
    cls = Class.forName(cls.getName());
    Field[] fieldlist = cls.getDeclaredFields();
    for (int i = 0; i < fieldlist.length; i++) {
    Field fld = fieldlist[i];
    String _key = fld.getName();
    Object _value = null;
    // System.out.println("name = " + fld.getName());
    // System.out.println("Type = " + fld.getType());
    Method getMethod = ObjectUtil.getMethod(obj.getClass(), fld.getName(), "get");
    if (getMethod != null) {
    _value = getMethod.invoke(obj, null);
    if (!String.class.getName().equals(fld.getType().getName())
    && !Long.class.getName().equals(fld.getType().getName())
    && !java.util.Date.class.getName().equals(fld.getType().getName())
    && !Integer.class.getName().equals(fld.getType().getName())
    && !Double.class.getName().equals(fld.getType().getName())
    && !Float.class.getName().equals(fld.getType().getName())
    && !BigDecimal.class.getName().equals(fld.getType().getName())
    && !(List.class.getName()).equals(fld.getType().getName())
    && !(ArrayList.class.getName()).equals(fld.getType().getName())
    && !(HashSet.class.getName()).equals(fld.getType().getName())
    && !(Map.class.getName()).equals(fld.getType().getName())
    && _value!=null) {
    //对象形式
    map.put(_key, getMapByClass0(_value,0));
    //对象值形式
    map.putAll(getMapByClass(_value,_key,0));
    continue;
    }
    }
    map.put(_key, _value);
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return map;
    }


    /**
    * @author jonas
    * @DATE (2015-3-9)
    * @param obj
    * @param index
    *            向下?层
    * @return
    */
    private static Map getMapByClass(Object obj,String zkey, int index) {
    Map map = null;
    if (index <= 1) {
    map = new HashMap();
    try {
    Class cls = obj.getClass();
    cls = Class.forName(cls.getName());
    Field[] fieldlist = cls.getDeclaredFields();
    for (int i = 0; i < fieldlist.length; i++) {
    Field fld = fieldlist[i];
    String _key = fld.getName();
    Object _value = null;
    Method getMethod = ObjectUtil.getMethod(obj.getClass(), fld.getName(), "get");
    if (getMethod != null) {
    _value = getMethod.invoke(obj, null);
    if (!String.class.getName().equals(fld.getType().getName())
    && !Long.class.getName().equals(fld.getType().getName())
    && !java.util.Date.class.getName().equals(fld.getType().getName())
    && !Integer.class.getName().equals(fld.getType().getName())
    && !Double.class.getName().equals(fld.getType().getName())
    && !Float.class.getName().equals(fld.getType().getName())
    && !BigDecimal.class.getName().equals(fld.getType().getName())
    && !(List.class.getName()).equals(fld.getType().getName())
    && !(ArrayList.class.getName()).equals(fld.getType().getName())
    && !(HashSet.class.getName()).equals(fld.getType().getName())
    && !(Map.class.getName()).equals(fld.getType().getName())
    && _value!=null) {
    _value=getMapByClass(_value,zkey,index+1);
    }
    }
    if (_value!=null) {
    _key=zkey!=null?zkey+"."+_key:_key;
    map.put(_key, _value);
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return map;
    }

    private static Map getMapByClass0(Object obj, int index) {
    Map map = null;
    if (index <= 1) {
    map = new HashMap();
    try {
    Class cls = obj.getClass();
    cls = Class.forName(cls.getName());
    Field[] fieldlist = cls.getDeclaredFields();
    for (int i = 0; i < fieldlist.length; i++) {
    Field fld = fieldlist[i];
    String _key = fld.getName();
    Object _value = null;
    Method getMethod = ObjectUtil.getMethod(obj.getClass(), fld.getName(), "get");
    if (getMethod != null) {
    _value = getMethod.invoke(obj, null);
    if (!String.class.getName().equals(fld.getType().getName())
    && !Long.class.getName().equals(fld.getType().getName())
    && !java.util.Date.class.getName().equals(fld.getType().getName())
    && !Integer.class.getName().equals(fld.getType().getName())
    && !Double.class.getName().equals(fld.getType().getName())
    && !Float.class.getName().equals(fld.getType().getName())
    && !BigDecimal.class.getName().equals(fld.getType().getName())
    && !(List.class.getName()).equals(fld.getType().getName())
    && !(ArrayList.class.getName()).equals(fld.getType().getName())
    && !(HashSet.class.getName()).equals(fld.getType().getName())
    && !(Map.class.getName()).equals(fld.getType().getName())
    && _value!=null) {
    _value=getMapByClass0(_value,index+1);
    }
    }
    map.put(_key, _value);
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return map;
    }


    public static List<Map> getListMapByListClass(List objList) {
    List<Map> list = new ArrayList<Map>();
    if (objList != null) {
    for (Object object : objList) {
    list.add(getMapByClass(object));
    }
    }
    return list;
    }


    /**
    * @author jonas 把List<Map>对象转换为Java(List)对象
    * @DATE (2015-3-10)
    * @param cls
    * @param paramMap
    * @return
    */
    public static List toListObjectByMap(Class cls, List<Map> listMap) {
    List returnList = null;
    if (listMap != null && listMap.size() > 0) {
    returnList = new ArrayList();
    for (Map map : listMap) {
    returnList.add(toObjectByMap(cls, map));
    }
    }
    return returnList;
    }


    /**
    * @author nc 把Map对象转换为Java对象
    * @DATE (2015-3-10)
    * @param cls
    * @param paramMap
    * @return
    */
    public static Object toObjectByMap(Class cls, Map paramMap) {
    try {
    Object object = cls.newInstance();
    if (paramMap!=null) {
    Map map = paramMap;
    for (Object key : map.keySet()) {
    String _key = key.toString();
    String value = MapUtils.getString(paramMap, _key);
    if (value != null && value.trim() != "" && !value.equals("")) {
    ClassByMap.loopSetFieldValue(_key, object, value);
    }
    }
    }
    return object;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }


    static class ClassByMap {
    private static void loopSetFieldValue(String key, Object obj, String value) throws Exception {
    if (key.indexOf(".") == -1) {
    Field field = getFieldObj(obj, key);
    if (field != null) {
    setFieldValue(field, obj, value.toString());
    }
    if (value!=null && value.startsWith("{") && value.endsWith("}")) {
    Map<String, String> tMap=null;
    try {
    tMap = (Map<String,String>) JSON.Decode(value.trim());
    } catch (Exception e) {
    }
    if (tMap!=null) {
    if (field != null) {
    Method getMethod = ObjectUtil.getMethod(obj.getClass(), field.getName(), "get");
    if (getMethod != null) {
    Object object = getMethod.invoke(obj, null);
    if (object == null) {
    object = field.getType().newInstance();
    Method setMethod = ObjectUtil.getMethod(obj.getClass(), field.getName(), "set");
    setMethod.invoke(obj, object);
    }
    for (String suffix : tMap.keySet()) {
    String _suffixValue=MapUtils.getString(tMap, suffix);
    if (suffix.indexOf(".") != -1) {
    loopSetFieldValue(suffix, object, _suffixValue);
    } else {
    Field _field = getFieldObj(object, suffix);
    if (_field != null) {
    setFieldValue(_field, object, _suffixValue);
    }
    }
    }
    }
    }
    }
    }
    } else {
    String prefix = key.substring(0, key.indexOf("."));
    String suffix = key.substring(key.indexOf(".") + 1, key.length());
    Field field = getFieldObj(obj, prefix);
    if (field != null) {
    Method getMethod = ObjectUtil.getMethod(obj.getClass(), field.getName(), "get");
    if (getMethod != null) {
    Object object = getMethod.invoke(obj, null);
    if (object == null) {
    object = field.getType().newInstance();
    Method setMethod = ObjectUtil.getMethod(obj.getClass(), field.getName(), "set");
    setMethod.invoke(obj, object);
    }
    if (suffix.indexOf(".") != -1) {
    loopSetFieldValue(suffix, object, value);
    } else {
    Field _field = getFieldObj(object, suffix);
    if (_field != null) {
    setFieldValue(_field, object, value);
    }
    }
    }
    }
    }
    }


    private static Field getFieldObj(Field[] fields, String key) {
    for (int i = 0; i < fields.length; i++) {
    Field field = fields[i];
    if (field.getName().equals(key)) {
    return field;
    }
    }
    return null;
    }


    private static Field getFieldObj(Object object, String key) {
    Field fields[] = object.getClass().getDeclaredFields();
    return getFieldObj(fields, key);
    }


    private static void setFieldValue(Field field, Object obj, String value)
    throws IllegalArgumentException, IllegalAccessException, ParseException {
    field.setAccessible(true);
    if (StringUtils.isBlank(value)) {
    return;
    }
    String fieldType = field.getType().getName();
    if (fieldType.equals("java.lang.String")) {
    field.set(obj, value);
    } else if (fieldType.equals("java.lang.Integer") || fieldType.equals("int")) {
    field.set(obj, StringUtil.toInteger(value));
    } else if (fieldType.equals("java.lang.Long") || fieldType.equals("long")) {
    field.set(obj, StringUtil.toLong(value));
    } else if (fieldType.equals("java.lang.Float") || fieldType.equals("float")) {
    field.set(obj, StringUtil.toFloat(value));
    } else if (fieldType.equals("java.lang.Double") || fieldType.equals("double")) {
    field.set(obj, StringUtil.toDouble(value));
    } else if (fieldType.equals("java.util.Date")) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
    field.set(obj, sdf.parse(value));
    } catch (Exception e) {
    try {
    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    field.set(obj, sdf.parse(value));
    } catch (Exception e1) {
    try {
    sdf = new SimpleDateFormat("yyyy-MM-dd");
    field.set(obj, sdf.parse(value));
    } catch (Exception e2) {
    }
    }
    }
    } else if (fieldType.equals("javax.xml.datatype.XMLGregorianCalendar")) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
    date = sdf.parse(value);
    } catch (Exception e) {
    try {
    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    date = sdf.parse(value);
    } catch (Exception e1) {
    try {
    sdf = new SimpleDateFormat("yyyy-MM-dd");
    date = sdf.parse(value);
    } catch (Exception e2) {
    }
    }
    }
    field.set(obj, DateUtil.dateToXMLGregorianCalendar(date));
    } else if (fieldType.equals("java.math.BigDecimal")) {
    field.set(obj, new BigDecimal(value));
    } else if (fieldType.equals("java.lang.Boolean") || fieldType.equals("boolean")) {
    field.set(obj, Boolean.valueOf(value));
    } else if (fieldType.equals("java.lang.Byte") || fieldType.equals("byte")) {
    field.set(obj, Byte.valueOf(value));
    } else if (fieldType.equals("java.lang.Short") || fieldType.equals("short")) {
    field.set(obj, Short.valueOf(value));
    } else {
    fieldType = field.getGenericType().toString();
    if (fieldType.equals("class java.lang.String")) {
    field.set(obj, value);
    } else if (fieldType.equals("class java.lang.Integer") || fieldType.equals("int")) {
    field.set(obj, Integer.valueOf(value));
    } else if (fieldType.equals("class java.lang.Long") || fieldType.equals("long")) {
    field.set(obj, Long.valueOf(value));
    } else if (fieldType.equals("class java.lang.Float") || fieldType.equals("float")) {
    field.set(obj, Float.valueOf(value));
    } else if (fieldType.equals("class java.lang.Double") || fieldType.equals("double")) {
    field.set(obj, Double.valueOf(value));
    } else if (fieldType.equals("class javax.xml.datatype.XMLGregorianCalendar")) {
    try {
    Date d = new Date(value);
    field.set(obj, convertToXMLGregorianCalendar(d));
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    } else if (fieldType.equals("class java.util.Date")) {
    try {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    field.set(obj, df.parse(value));
    } catch (Exception e) {
    try {
    field.set(obj, new Date(value));
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    } else if (fieldType.equals("class java.math.BigDecimal")) {
    field.set(obj, new BigDecimal(value));
    } else if (fieldType.equals("class java.lang.Boolean") || fieldType.equals("boolean")) {
    field.set(obj, Boolean.valueOf(value));
    } else if (fieldType.equals("class java.lang.Byte") || fieldType.equals("byte")) {
    field.set(obj, Byte.valueOf(value));
    } else if (fieldType.equals("class java.lang.Short") || fieldType.equals("short")) {
    field.set(obj, Short.valueOf(value));
    }
    }
    }
    }


    public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar gc = null;
    try {
    gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return gc;
    }


    public Date convertToDate(XMLGregorianCalendar cal) throws Exception {
    GregorianCalendar ca = cal.toGregorianCalendar();
    return ca.getTime();
    }
    }

    展开全文
  • java中对象转map

    2018-05-30 13:33:28
    package org.kxtkx.portal.utils; import java.lang.reflect.Field; import java.util.HashMap;... * 描述:java中对象转map * @author wangzhiming * @created in 2018-05-29 */ public cla...
    package org.kxtkx.portal.utils;
    
    import java.lang.reflect.Field;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 描述:java中对象转map
     * @author wangzhiming 
     * @created in 2018-05-29
     */
    public class objAnalys {
     
     public static Map ConvertObjToMap(Object obj){
      Map<String,Object> reMap = new HashMap<String,Object>();
      if (obj == null) 
       return null;
      //获取实体中声明的所有字段名字
      Field[] fields = obj.getClass().getDeclaredFields();
      try {
       for(int i=0;i<fields.length;i++){
        try {
         Field f = obj.getClass().getDeclaredField(fields[i].getName());
         让我们在用反射时访问私有变量,如果setAccessible(false):不允许通过反射访问该字段
         f.setAccessible(true);
         //获取属性值
         Object o = f.get(obj);
        //添加至map中
         reMap.put(fields[i].getName(), o);
        } catch (NoSuchFieldException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } catch (IllegalArgumentException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } catch (IllegalAccessException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
       }
      } catch (SecurityException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } 
      return reMap;
     }
     
     public static void main(String[] args) {
      Admin a = new Admin();
      a.setCPassword("wzm1994");
      a.setCUsername("张三");
      Map m = ConvertObjToMap(a);
      System.out.println(m);
     }
    }
    

    展开全文
  • 前提需要引入jackson包,然后调用 Map resultMap = new ObjectMapper().convertValue(object, Map.class); 即可
  • JavaObject转换为List类型

    万次阅读 2020-05-19 15:57:33
    解析数据的时候map.get(key)所获取到的类型为Object。此时,需要转换成我们所需要的数据类型进行使用。 类型转换 在类型转换工程中,常见的转换方式为强制转换。如(String)map.get(key),(int)map.get(key)等。在是...
  • Object转Map的几个坑

    千次阅读 2019-03-07 16:40:15
    这里总结了三种Object转Map的方法 1、利用反射getDeclaredFields和getFields /** * 对传入的对象进行数据清洗,将属性值为null和""的去掉,其他字段名和属性值存入map集合 */ public Map<String,Object> ...
  • java解析json转Map

    千次阅读 2017-08-23 16:55:19
    前段时间在做json报文处理的时候,写了一个针对不同格式json转map的处理工具方法,总结记录如下:1、单节点单层级、单节点多层级json转mapimport java.util.ArrayList; import java.util.HashMap; import java.util....
  • JAVA 解析 XML Map

    千次阅读 2019-05-29 17:42:07
    import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; /** ...
  • 这是我对java反射机制的一点认识,利用反射可以将map集合与object对象进行转化,我想如果可以的话可以进一步改善当做一个框架来编写
  • JSON与JAVA数据的转换(JSON 即 JavaScript ObjectNatation,它是一种轻量级的数据交换格式,非常适合于服务器...JSONObjectjo = JSONObject.fromObject(map); 常见的java代码转换成json 1. List集合转换成json代
  • JavaMapObject

    千次阅读 2017-07-01 16:03:36
    JavaMapObject有三种方法:1.使用 org.apache.commons.beanutils 进行转换;使用简单方便,但需要引入第三方包。2.使用 Introspector 进行转换;getPropertyDescriptors()根据方法来得到属性信息,所有符合...
  • 1 /** 2 * 将map转换为一个对象 3 * 4 * @param map 5 * @param beanClass 6 * @return 7 * @throws Exception 8 */ 9 public static Object mapToObject(Map&l...
  • java xml转map map转xml 带属性

    万次阅读 2016-11-23 19:25:56
    参考效果:xmljson java xmljson jsonxml ...   java xml转map Java代码  package xml2map;    import java.io.File;  import java.io.IOException; 
  • Java对象转Map的解决办法

    万次阅读 2017-03-31 17:02:41
    Java Object转Map,可使用 1:org.apache.commons.beanutils.BeanUtils中的BeanUtils.describe(Obj);方法, 2:使用Dozer(JavaBean的映射工具),功能比①强悍,强烈推荐,详解请移步本人博客链接:...
  • java 对象转map,map转对象

    千次阅读 2017-10-10 11:28:34
    java对象转map: /** * JavaBean对象转化成Map对象 * * @param javaBean * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map java2Map(Object javaBean) { Map map = ...
  • 根据情况设定获取fid、id和设定子树的方法名。默认的方法名看代码注释。 public class MenuTreeUtils<T> { private List<T> treeList; //获取fid 的方法名 private String getFidMethod = "getFid...
  • java bean转map

    千次阅读 2018-01-18 16:50:42
    自:http://blog.csdn.net/q358543781/article/details/50176953javabean与map的转换有很多种方式,比如:1、通过ObjectMapper先将bean转换为json,再将json转换...不推荐使用2、通过java反射,获取bean类的属性和值,
  • java工具类-Java对象转换成Map

    千次阅读 2019-09-10 16:58:59
    package ... import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Map转换工具类 */ public class ...
  • 转换规则为:Map中的key是新对象的属性名,Map中的value是新对象中的属性值 import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Field;... * 将map转换为object,转换全部属性(按照...
  • JavaMap转对象,对象转Map

    千次阅读 2018-07-09 16:25:44
    1.对象转Map public static Map java2Map(Object javaBean) { Map map = new HashMap(); try { // 获取javaBean属性 BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClas...
  • package com.libstar.sd.utils; import com.libstar.lsp.support.util.DateUtils; import com.libstar.lsp.support.util.JsonUtils; import ... import java.lang.reflect...
  • 利用反射将Java对象Map集合 将java对象封装到map集合中有两种方案: ...利用反射将java实体对象map集合,首先获取字节码对象Class,然后获取对象的所有属性值,其次获取对象的所有属性值,最...
  • java 标准格式String转Map

    千次阅读 2018-08-08 10:32:17
    //标准格式的Map格式,如果json传中有'[',']','{','}'用URLEncoder进行加密解密处理 //{aaa=avlaue, json={ "data": { "tyf": [{ "upCount": 81, "merNum": "no05-...
  • JAVA实现map转成XML格式

    千次阅读 2019-12-03 10:22:24
    JAVA实现map集合成XML格式 import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.dom4j.Document; import org.dom4j.DocumentException; import org...
  • java对象转换map

    千次阅读 2017-06-14 20:22:15
    对象转MAP背景介绍 今天在项目研发的过程中遇到这样一个需求,在一个统一处理类的入口要将所有后面处理流程需要用到的值统一塞进上下文的MAP对象中,这其中就包括了一持久层的DO对象。  如果对于对象进行逐个遍历...
  • java工具类-bean转map

    千次阅读 2020-06-22 21:46:56
    工作常常遇到将java的Bean对象转化为Map,或者将Map转为Bean对象。 常见的手段 通过json工具,将Beanjson,再将json转Map 效率低 jdk的反射,获取类的属性,进行转化 比较麻烦,书写代码比较多 通过工具类...
  • import java.util.List; /** * 开发公司:青岛海豚数据技术有限公司 * 版权:青岛海豚数据技术有限公司 * &amp;amp;lt;p&amp;amp;gt; * User * * @author 刘志强 * @created Cr...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 343,523
精华内容 137,409
关键字:

java获取object转map

java 订阅