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;
    }
相关文章
相关标签/搜索