JAVA中,各种数据转换为对象的原理

package com.it.code.req_string_map_obj;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
public class demo002 {

    /**
     * 把对象toString
     * 
     * @param object 对象
     * @return 对象转换为String的类型
     * @throws Exception
     */
    public static String toString(Object object)     {
        if (object == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        Class c = object.getClass();
        Method[] methods = c.getMethods();
        Field[] fields = c.getDeclaredFields();
        String fieldName, methodName;
        Method method;
        Field field;
        for (int i = 0; i < fields.length; i++) {
            field = fields[i];
            fieldName = field.getName();
            for (int j = 0; j < methods.length; j++) {
                method = methods[j];
                methodName = method.getName();
                if (methodName.toUpperCase().endsWith("GET" + fieldName.toUpperCase())) {
                    try {
                        sb.append(fieldName + "=" + method.invoke(object));
                    } catch (Exception e) {
                         System.out.println("映射新对象" + c + "失败,列名:" + fieldName + ",方法名:" + methodName + "/n" + e);
                    }
                    break;
                }
            }
            if (i < fields.length - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }
    //测试tostring
    public static void main01(String[] args) {
    	Person person = new Person();
    	person.setId("001");
    	person.setName("002");
    	System.out.println(toString(person));
    	 
	}
    //测试基类
   static class Person {
    	
    	
    	private String id;
    	private String name ;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
    	
    	
    }
    /**
     * 把String类型转换成map(只需键值对)
     * 
     * @param stringByMap 键值对的形式,中间用英文逗号分隔
     * @return map
     */
    public static Map refertForMap(String stringByMap) {
        // 验证输入,若是空,返回null
      /*  if (Validate.isNull(stringByMap)) {
            return null;
        }*/
        // 根据“,”分隔开每一组数值
        String[] keyValues = stringByMap.split(",");
        // 定义返回类型
        Map map = new HashMap();
        for (int i = 0; i < keyValues.length; i++) {
            // 根据“=”分隔开key和value值
            // 存放每一组数值
            String[] key_value = keyValues[i].split("=");
            // 如果不存在key或value则继续下次组装
            if (key_value.length != 2) {	
                continue;
            }
            // 存放key和value
            //网站认证中心
            String key;
            // 把key值去除空格,并转成大写
            try {
                key = key_value[0].trim().toUpperCase();
            } catch (RuntimeException e) {
                continue;
            }
            // 获取value值
            String value = key_value[1];
            // 存入map
            map.put(key, value);
        }
        // 返回map
        return map;
    }
    //测试
    public static void main02(String[] args) {
    	String string = "id=1,name=2";
    	Map<String, Object> map =refertForMap(string);
     for(String key:map.keySet()){
    	 
    	 System.out.println(key+"="+map.get(key));
     }
    
    }
    /**
     * 把String类型转换成对象
     * 
     * @param stringByObject 键值对的形式,中间用英文逗号分隔
     * @param obj            要映射的对象
     * @return Object 映射后的对象
     * @throws Exception
     */
    public static Object refertForObject(String stringByObject, Object obj) {
        if ("java.lang.Class".equals(obj.getClass().getName())) {
            System.out.println("Object不应为java.lang.Class类型");
        }
        // 验证输入,若是空,返回null
      /*  if (Validate.isNull(stringByObject)) {
            return null;
        }*/
        // 根据“,”分隔开每一组数值
        String[] keyValues = stringByObject.split(",");
        // 存放key和value
        String key, value;
        // 定义返回类型
        for (int i = 0; i < keyValues.length; i++) {
            // 根据“=”分隔开key和value值
            // 存放每一组数值
            String[] key_value = keyValues[i].split("=");
            // 如果不存在key或value则继续下次组装
            if (key_value.length != 2) {
                continue;
            }
            // 把key值去除空格,并转成大写
            try {
                key = key_value[0].trim().toUpperCase();
            } catch (RuntimeException e) {
                continue;
            }
            // 获取value值
            value = key_value[1];
            // 存入map
            setObject(key, value, obj);
        }
        // 返回map
        return obj;
    }

    //
    public static void main(String[] args) {
    	String string = "id=1,name=2";
    	Person person = new Person();
    	person =(Person)refertForObject(string,person);
    	System.out.println(person.getId());
    	System.out.println(person.getName());
	}
    /**
     * 把request映射成map
     * 
     * @param request
     * @return
     * @throws RefertException
     */
    public static Map refertForMapByRequest(HttpServletRequest request)  {
    	  // 存放符合条件的name-value映射值  
    	Map initMap = new HashMap();
    	try {
            // 获取页面上的所有name值
            Enumeration pNames = request.getParameterNames();
          
         
            // 获取页面的操作类型
            // 遍历页面所有的name值
            while (pNames.hasMoreElements()) {
                // 获取当前要验证的name值
                String name = (String) pNames.nextElement();
                String value = request.getParameter(name);
                initMap.put(name.toUpperCase(), value);
            }
            // 返回map
            return initMap;
        } catch (Exception e) {
        	System.out.println("获取页面信息失败\n" + e);
        	 return initMap;
        }
    }

    /**
     * 把request映射成Object
     * 
     * @param request
     * @param obj
     * @return
     * @throws RefertException
     */
    public static Object refertForObjectByRequest(HttpServletRequest request, Object obj) {
        try {
            Map map = refertForMapByRequest(request);
            refertForObjectByMap(map, obj);
            return obj;
        } catch (Exception e) {
        	System.out.println(e);
        	 return obj;
        }
    }

    /**
     * 把Object映射成Map
     * 
     * @param object
     * @return
     * @throws RefertException
     */
    public static Map<String, Object> refertForMapByObject(Object object)  {
        if (object == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Class c = object.getClass();
        Method[] methods = c.getMethods();
        Field[] fields = c.getDeclaredFields();
        String fieldName, methodName;
        Method method;
        Field field;
        for (int i = 0; i < fields.length; i++) {
            field = fields[i];
            fieldName = field.getName();
            for (int j = 0; j < methods.length; j++) {
                method = methods[j];
                methodName = method.getName();
                if (methodName.toUpperCase().endsWith("GET" + fieldName.toUpperCase())) {
                    try {
                        map.put(fieldName, method.invoke(object));
                    } catch (Exception e) {
                    	System.out.println("映射新对象" + c + "失败,列名:" + fieldName + ",方法名:" + methodName + "/n" + e);
                    }
                    break;
                }
            }
        }
        return map;
    }

    /**
     * 把map映射成对象
     * 
     * @param map 映射源内容
     * @param obj 映射成的对象
     * @return obj
     * @throws RefertException
     */
    public static Object refertForObjectByMap(Map<Object, Object> map, Object obj)  {
        try {
        	//验证
           /* if (Validate.isNull(map))
                return null;
            if (Validate.isNull(obj))
                return null;*/
            if ("java.lang.Class".equals(obj.getClass().getName()))
            	System.out.println("Object不应为java.lang.Class类型");
            for (Map.Entry<Object, Object> e : map.entrySet()) {
                String key = e.getKey().toString();
                Object value = e.getValue();
                setObject(key, value, obj);
            }
            return obj;
        } catch (Exception e) {
        	System.out.println(e);
        	 return obj;
        }
    }

    /**
     * 映射对象
     * 
     * @param name  映射的名称
     * @param value 映射的值
     * @param obj   映射的对象
     * @return 映射完成的对象
     * @throws RefertException
     */
    private static Object setObject(String name, Object value, Object obj) {
        Class c = obj.getClass();
        String setName;
        name = "SET" + name;
        name = name.toUpperCase();
        Method[] methods = c.getDeclaredMethods();
        Method method;
        String valueType = value.getClass().getName();
        for (int i = 0; i < methods.length; i++) {
            method = methods[i];
            setName = method.getName().toUpperCase();
            if (name.equals(setName)) {
                Class[] pts = method.getParameterTypes();
                if (pts.length != 1) {
                	System.out.println("映射新对象" + c + "失败,name=" + name + "的传入参数不唯一,映射失败\n");
                }
                String parameterType = pts[0].getTypeName();
                if (parameterType.equals(valueType)) {
                    // 对象接收值类型与传入值类型相同
                } else if ("java.util.Map".equals(parameterType) && Map.class.isAssignableFrom(value.getClass())) {
                    // 对象接收值类型map是传入值的父类
                } else if ("java.util.List".equals(parameterType) && List.class.isAssignableFrom(value.getClass())) {
                    // 对象接收值类型list是传入值的父类
                } else if ("java.lang.Object".equals(parameterType)) {
                    // 对象接收值类型object
                } else if ("java.lang.String".equals(value.getClass().getName())) {
                    try {
                        if ("byte".equals(parameterType)) {
                            value = Byte.valueOf((String) value);
                        } else if ("short".equals(parameterType)) {
                            value = Short.valueOf((String) value);
                        } else if ("int".equals(parameterType)) {
                            value = Integer.valueOf((String) value);
                        } else if ("long".equals(parameterType)) {
                            value = Long.valueOf((String) value);
                        } else if ("float".equals(parameterType)) {
                            value = Float.valueOf((String) value);
                        } else if ("double".equals(parameterType)) {
                            value = Double.valueOf((String) value);
                        } else if ("char[]".equals(parameterType)) {
                            value = value.toString().toCharArray();
                        } else if ("boolean".equals(parameterType)) {
                            value = Boolean.valueOf((String) value);
                        } else if ("double".equals(parameterType)) {
                            value = Double.valueOf((String) value);
                        } else {
                            // map不支持(map内嵌套map,对map根据逗号进行拆分时出错)
                        	System.out.println();
                        }
                    } catch (Exception e) {
                        StringBuffer refertLogger = new StringBuffer();
                        refertLogger.append("映射新对象" + c + "失败,");
                        refertLogger.append("name=" + name + ",");
                        refertLogger.append(valueType + "强转为" + parameterType + "失败");
                        System.out.println(refertLogger.toString());
                    }
                } else {
                    StringBuffer refertLogger = new StringBuffer();
                    refertLogger.append("映射新对象" + c + "失败,");
                    refertLogger.append("name=" + name + ",");
                    refertLogger.append(valueType + "强转为" + parameterType + "失败");
                    System.out.println(refertLogger.toString());
                }
                try {
                    method.invoke(obj, value);
                    break;
                } catch (Exception e) {
                    StringBuffer refertLogger = new StringBuffer();
                    refertLogger.append("映射新对象" + c + "失败,");
                    refertLogger.append("name=" + name + "。");
                    System.out.println(refertLogger.toString());
                }
            }
        }
        return obj;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值