Метод clone () не генерирует исключение RuntimeException для объекта класса не реализованного Cloneable - PullRequest
0 голосов
/ 27 марта 2012

Контрольный пример (версия jdk: oracle 1.6.0_31)

public class TestCloneable{
    public TestCloneable clone(){
        return new TestCloneable();
    }
}


public static void main(String[] args) {
    TestCloneable testObj = new TestCloneable();
    TestCloneable testObj2 = new TestCloneable();

    System.out.println(testObj.clone());

    Hashtable<Integer, TestCloneable> ht = new Hashtable<Integer, TestCloneable>();
    ht.put(1, testObj);
    ht.put(2, testObj2);
    System.out.println(ht.clone());

    HashMap<Integer, TestCloneable> hm = new HashMap<Integer, TestCloneable>();
    hm.put(1, testObj);
    hm.put(2, testObj2);
    System.out.println(hm.clone());

}

Ни одна из этих строк не дает CloneNotSupportedException во время выполнения, что противоречит спецификации Java для метода клонирования: <pre> /** * @exception CloneNotSupportedException if the object's class does not * support the <code>Cloneable интерфейс.Подклассы ... * /

Где ошибка?

1 Ответ

3 голосов
/ 27 марта 2012

Согласно javadocs для hashmap :

clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

Поэтому метод clone() никогда не вызывается в вашем классе.

Более того, если вы хотите получить выгодуиз поведения clone() метода в Object и исключения, выдаваемого, когда объект не реализует Cloneable, вы должны вызвать super.clone() в переопределенном методе clone вашего класса.

...