java.lang.reflect.InvocationTargetException

關於java.lang.reflect.InvocationTargetException,平時習慣用Clone工具方法對拷對象,今天突然蹦出了這個異常,乍看還覺得是字段匹配的有問題,一看還不是,而後比較一下對象的定義,發現一個對象裏有自定義的有參構造方法,沒有把無參的構造方法加上,看到這估計應該是這個形成的,由於克隆的時候要新建立一個對象,可是發現沒有無參構造方法,因而就出現了上面錯誤;因而加上無參構造方法再試一下,done。java

   通常無參構造方法不加也沒事,但仍是加上的好,這個仍是編碼習慣的問題。工具

public static <T, E> E clone(T source, Class<E> classType) {

        if (source == null) {
            return null;
        }
        E targetInstance = null;
        try {
            targetInstance = classType.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        BeanUtils.copyProperties(source, targetInstance);
        return targetInstance;
    }
相關文章
相關標籤/搜索