Java: Why shouldn't clone() be used for defensive copying?

前端 未结 3 540
醉梦人生
醉梦人生 2021-01-13 09:19

In Effective Java (Chapter 7), it says

Note also that we did not use Date’s clone method to make the defensive copies. Because Date is nonfinal, the c

3条回答
  •  [愿得一人]
    2021-01-13 09:30

    Consider this code:

    public class MaliciousDate extends Date { /** malicious code here **/ }
    
    public class SomeClass {
        public static void main(String[] args) {
            MaliciousDate someDate = new MaliciousDate();
            Date copyOfMaliciousDate = someDate;
            Date anotherDate = copyOfMaliciousDate.clone();
        }
    }
    

    Since copyOfMaliciousDate is of type Date, you can call clone() and it will return a Date object, but calling clone on copyOfMaliciousDate executes the code written in the MaliciousDate class because the instance stored in copyOfMaliciousDate is a MaliciousDate.

提交回复
热议问题