java对象转map

/**
	 * java对象转map
	 * @param obj
	 * @return
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public static Map<String,Object> obj2Map(Object obj) throws Exception {
	    Map<String,Object> result = new HashMap<String,Object>();
	    //一些基础引用类型
	    List<String> baseType = Arrays.asList(new String[]{
	            "java.lang.Boolean",
	            "java.lang.Byte",
	            "java.lang.Character",
	            "java.lang.Double",
	            "java.lang.Float",
	            "java.lang.Integer",
	            "java.lang.Long",
	            "java.lang.Short",
	            "java.lang.String",
	            "java.math.BigDecimal"
	    });
	    Class<?> clazz = obj.getClass();
	    Field[] fields = clazz.getDeclaredFields();
	    for(int i = 0,len = fields.length; i<len; i++) {
	        fields[i].setAccessible(true);
	        if(baseType.contains(fields[i].getType().getName())) {
	            //类型判断,基本类型判断、基础引用类型判断、数组判断
	            result.put(fields[i].getName(), fields[i].get(obj));
	        } else if(isBaseArray(fields[i].get(obj))) {
	            //数组
	            result.put(fields[i].getName(), fields[i].get(obj));
	        } else {
	            Object value = fields[i].get(obj);
	            result.put(fields[i].getName(), obj2Map(value));
	        }
	    }
	    return result;
	}
	
	private static Boolean isBaseArray(Object obj) {
	    if(obj instanceof Integer[] || obj instanceof int[]) {
	        return true;
	    }
	    if(obj instanceof Boolean[] || obj instanceof boolean[]) {
            return true;
        }
	    if(obj instanceof Byte[] || obj instanceof byte[]) {
            return true;
        }
	    if(obj instanceof Character[] || obj instanceof char[]) {
            return true;
        }
	    if(obj instanceof Double[] || obj instanceof double[]) {
            return true;
        }
	    if(obj instanceof Float[] || obj instanceof float[]) {
            return true;
        }
	    if(obj instanceof Long[] || obj instanceof long[]) {
            return true;
        }
	    if(obj instanceof Short[] || obj instanceof short[]) {
            return true;
        }
	    if(obj instanceof String[]) {
            return true;
        }
	    if(obj instanceof BigDecimal[]) {
            return true;
        }
	    if("java.util.ArrayList".equals(obj.getClass().getName())) {
	        return true;
	    }
	    return false;
	}

  

posted on 2018-10-26 10:59  康纳酱  阅读(586)  评论(0编辑  收藏  举报

导航