学习4 对象克隆

来源:互联网 发布:高大上ppt制作技巧知乎 编辑:程序博客网 时间:2024/05/29 03:10
 
    /**     * 对象克隆接口     * @param <T> <T>     * @param from from     * @param dstType dstType     *      * @return T     */    public static <T> T cloneObject(Object from, Class<T> dstType)    {        if (null != from && null != dstType)        {            try            {                T result = dstType.newInstance();                copyProperties(from, result);                return result;            }            catch (InstantiationException e)            {                return null;            }            catch (IllegalAccessException e)            {                return null;            }        }        return null;    }        /**     * 对象的属性复制接口     *      * @param from from     * @param to to     * @return boolean     */    public static boolean copyProperties(Object from, Object to)    {        if (null != from && null != to)        {            Method[] toMethods = to.getClass().getMethods();            HashMap<String, Method> toMethodMap = new HashMap<String, Method>();            for (Method method : toMethods)            {                toMethodMap.put(method.getName(), method);            }            try            {                Method[] methods = from.getClass().getMethods();                for (Method fromMethod : methods)                {                    String fieldName = getFieldByMethod(fromMethod);                    if (null != fieldName)                    {                        Method toMethod = toMethodMap.get("set" + fieldName);                        if (null != toMethod)                        {                            toMethod.invoke(to, fromMethod.invoke(from, new Object[0]));                        }                    }                }            }            catch (IllegalArgumentException e)            {                return false;            }            catch (IllegalAccessException e)            {                return false;            }            catch (InvocationTargetException e)            {                return false;            }        }        return true;    }

原创粉丝点击