java.lang.reflect.InvocationTargetException

关于java.lang.reflect.InvocationTargetException,平时习惯用Clone工具方法对拷对象,今天忽然蹦出了这个异常,乍看还以为是字段匹配的有问题,一看还不是,然后比较一下对象的定义,发现一个对象里有自定义的有参构造方法,没有把无参的构造方法加上,看到这估计应该是这个造成的,因为克隆的时候要新创建一个对象,但是发现没有无参构造方法,于是就出现了上面错误;于是加上无参构造方法再试一下,done。

   一般无参构造方法不加也没事,但还是加上的好,这个还是编码习惯的问题。

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;
    }
原文地址:https://www.cnblogs.com/hsuchan/p/7119857.html