Why is #clone() not in the Cloneable interface?

后端 未结 3 2028
盖世英雄少女心
盖世英雄少女心 2021-01-31 20:13

I was reading up on performing a deep-copy of an array correctly, however I was confused about how the #clone() is implemented. It is a member of the java.lan

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 20:29

    clone() method is unnecessary, every object could invoke Object.clone method by reflect, so an object can be cloned depends on whether to implement Cloneable interface. This is for a security reason. You can simply clone an object which implements Cloneable by this util:

    @SuppressWarnings("unchecked")
    public static  T clone(Cloneable obj) {
        T rtn = null;
        try {
            Method method = Object.class.getDeclaredMethod("clone");
            method.setAccessible(true);
            rtn = (T) method.invoke(obj);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return rtn;
    }
    

提交回复
热议问题