当前位置: 移动技术网 > IT编程>开发语言>Java > 映射篇:request-String-Object-Map之间相互转化(程序员的成长之路---第5篇)

映射篇:request-String-Object-Map之间相互转化(程序员的成长之路---第5篇)

2019年01月14日  | 移动技术网IT编程  | 我要评论

为什么写这一篇

问题一:jdbc连接数据库返回的对象是resultset,如何把resultset对象中的值转换为我们自建的各种实体类?

我估计,80%的程序员会写jdbc数据库连接,但开发项目依然用spring、hibernate、 mybatis等开源框架封装的数据库连接。

在你能写一套足够好的数据库连接池进行数据库增删改查的时候,我并不认为开源框架会比你写的数据库连接效率快多少。那大部分人为什么没有用自己写的数据库连接池?

“拿来主义”,确实让我们的工作轻松了很多。

当我们被简单的“拿来主义”充满头脑的时候,一旦出现开源框架的数据库连接不能满足我们的项目需求的时候,谁来负责底层框架的修改?

...其他的不多说了,总之每个人都有不同的推脱理由。

jdbc连接数据库返回的对象是resultset,如何能把resultset对象中的值转换为我们自建的各种实体类的值呢?

问题二:

user user = new user();
user.setname("张三");
user.setage(20);
user.setadress("中国山东济南");
system.out.println(user);
以上代码,
希望打印出的結果:name=张三,age=20,adress=中国山东济南
实际打印出的結果:com.keji10.core.commons.user@7852e922

  总之说了这么多。只是为了体现映射在我们日常敲代码的过程中的重要性 --<-<-<@

 类方法:

 

类代码:

package com.keji10.core.commons;

import java.lang.reflect.field;
import java.lang.reflect.method;
import java.util.enumeration;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import javax.servlet.http.httpservletrequest;

import com.keji10.core.exception.refertexception;

/**
 * 类描述:
 * 
 * @since 1.5
 * @version 1.0
 * @author xuanly
 * 
 */
public abstract class beanhelper {

    /**
     * 把对象tostring
     * 
     * @param object 对象
     * @return 对象转换为string的类型
     * @throws exception
     */
    public static string tostring(object object) throws refertexception {
        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) {
                        throw new refertexception("映射新对象" + c + "失败,列名:" + fieldname + ",方法名:" + methodname + "/n" + e);
                    }
                    break;
                }
            }
            if (i < fields.length - 1) {
                sb.append(",");
            }
        }
        return sb.tostring();
    }

    /**
     * 把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;
    }

    /**
     * 把string类型转换成对象
     * 
     * @param stringbyobject 键值对的形式,中间用英文逗号分隔
     * @param obj            要映射的对象
     * @return object 映射后的对象
     * @throws exception
     */
    public static object refertforobject(string stringbyobject, object obj) throws refertexception {
        if ("java.lang.class".equals(obj.getclass().getname())) {
            throw new refertexception("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;
    }

    /**
     * 把request映射成map
     * 
     * @param request
     * @return
     * @throws refertexception
     */
    public static map refertformapbyrequest(httpservletrequest request) throws refertexception {
        try {
            // 获取页面上的所有name值
            enumeration pnames = request.getparameternames();
            // 存放符合条件的name-value映射值
            map initmap = new hashmap();
            // 获取页面的操作类型
            // 遍历页面所有的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) {
            throw new refertexception("获取页面信息失败\n" + e);
        }
    }

    /**
     * 把request映射成object
     * 
     * @param request
     * @param obj
     * @return
     * @throws refertexception
     */
    public static object refertforobjectbyrequest(httpservletrequest request, object obj) throws refertexception {
        try {
            map map = refertformapbyrequest(request);
            refertforobjectbymap(map, obj);
            return obj;
        } catch (exception e) {
            throw new refertexception(e);
        }
    }

    /**
     * 把object映射成map
     * 
     * @param object
     * @return
     * @throws refertexception
     */
    public static map<string, object> refertformapbyobject(object object) throws refertexception {
        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) {
                        throw new refertexception("映射新对象" + 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) throws refertexception {
        try {
            if (validate.isnull(map))
                return null;
            if (validate.isnull(obj))
                return null;
            if ("java.lang.class".equals(obj.getclass().getname()))
                throw new refertexception("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) {
            throw new refertexception(e);
        }
    }

    /**
     * 映射对象
     * 
     * @param name  映射的名称
     * @param value 映射的值
     * @param obj   映射的对象
     * @return 映射完成的对象
     * @throws refertexception
     */
    private static object setobject(string name, object value, object obj) throws refertexception {
        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) {
                    throw new refertexception("映射新对象" + 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根据逗号进行拆分时出错)
                            throw new refertexception();
                        }
                    } catch (exception e) {
                        stringbuffer refertlogger = new stringbuffer();
                        refertlogger.append("映射新对象" + c + "失败,");
                        refertlogger.append("name=" + name + ",");
                        refertlogger.append(valuetype + "强转为" + parametertype + "失败");
                        throw new refertexception(refertlogger.tostring());
                    }
                } else {
                    stringbuffer refertlogger = new stringbuffer();
                    refertlogger.append("映射新对象" + c + "失败,");
                    refertlogger.append("name=" + name + ",");
                    refertlogger.append(valuetype + "强转为" + parametertype + "失败");
                    throw new refertexception(refertlogger.tostring());
                }
                try {
                    method.invoke(obj, value);
                    break;
                } catch (exception e) {
                    stringbuffer refertlogger = new stringbuffer();
                    refertlogger.append("映射新对象" + c + "失败,");
                    refertlogger.append("name=" + name + "。");
                    throw new refertexception(refertlogger.tostring());
                }
            }
        }
        return obj;
    }
}

 

生命不息,奋斗不止

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网