Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

How does Cloneable work in Java and how do I use it?

I would like to know the following:

  1. Cloneable means we can have a clone or a copy of objects, by implementing the Cloneable interface. What are the advantages and disadvantages of doing that?
  2. How does the recursive cloning happen if the object is a composite object?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first thing you should know about Cloneable is - don't use it.

It is very hard to implement cloning with Cloneable right, and the effort is not worth it.

Instead of that use some other options, like apache-commons SerializationUtils (deep-clone) or BeanUtils (shallow-clone), or simply use a copy-constructor.

See here for the views of Josh Bloch about cloning with Cloneable, which explains the many drawbacks of the approach. (Joshua Bloch was a Sun employee, and led the development of numerous Java features.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...