java.util.Date clone or copy to not expose internal reference

前端 未结 3 935
小鲜肉
小鲜肉 2020-12-02 12:03

It is best practice not to expose the internal references of an Object (Entity). So if an Object has a field of type java.util.Date then for example the get

3条回答
  •  广开言路
    2020-12-02 12:35

    Read Effective Java. The preferred way to create copies is to use the copy constructor approach.

    Bill Venners: In your book you recommend using a copy constructor instead of implementing Cloneable and writing clone. Could you elaborate on that?

    Josh Bloch: If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.

提交回复
热议问题