根据指定方法的参数去构造一个新的对象的拷贝并将他返回

来源:互联网 发布:期货交易软件分析决策 编辑:程序博客网 时间:2024/04/27 23:21

 **  
     * 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
     * @param obj 原始对象
     * @return 新对象
     * @throws NoSuchMethodException   
     * @throws InvocationTargetException   
     * @throws IllegalAccessException   
     * @throws InstantiationException   
     * @throws SecurityException   
     * @throws IllegalArgumentException   
     */
    @SuppressWarnings("unchecked")
    public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
                    InvocationTargetException, NoSuchMethodException
    {
        //获得对象的类型   
        Class classType = obj.getClass();

        //通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法   
        Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});

        //获得对象的所有属性   
        Field[] fields = classType.getDeclaredFields();

        for(int i = 0; i < fields.length; i++)
        {
            //获取数组中对应的属性   
            Field field = fields[i];

            String fieldName = field.getName();
            String stringLetter = fieldName.substring(0, 1).toUpperCase();

            //获得相应属性的getXXX和setXXX方法名称   
            String getName = "get" + stringLetter + fieldName.substring(1);
            String setName = "set" + stringLetter + fieldName.substring(1);

            //获取相应的方法   
            Method getMethod = classType.getMethod(getName, new Class[]{});
            Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});

            //调用源对象的getXXX()方法   
            Object value = getMethod.invoke(obj, new Object[]{});

            //调用拷贝对象的setXXX()方法   
            setMethod.invoke(objectCopy, new Object[]{value});
        }

        return objectCopy;
    }

原创粉丝点击