how to create clone of an object which does not implement Cloneable
I have to clone an object which does not implement Cloneable interface how to do this.
Actually in my project I am using JCChart .now my class extends MultiChart and I have to craete the deep copy of my class. I am able to clone my class object but how to clone Objects of MultiChart. like I also have to clone Legends of objects , Footer of Object, Header 开发者_JAVA百科of Object.
If your class is Serializable
than you can serialize the object to ByteStream and Deserialize that stream to a new object.
You wrote:
I have to clone an object which does not implement
Cloneable
interface how to do this.
The requirement for clone to work is that the class provides a clone()
method that is visible in the context that you want to call it. That class does not have to
implement Cloneable
. It could implement the clone()
method to explicitly use new
and then initialize the new object via the constructor and setter calls. (The Cloneable
interface is a "flag" interface that enables the default shallow cloning mechanism implemented by the java.lang.Object.clone()
method.)
On the topic of cloning without using clone, alternatives include:
- using a copy constructor,
- using a regular constructor and a sequence of getter and setter calls, or
- by serializing and deserializing the object.
These approaches all have limitations; e.g. availability of appropriate constructors, getters, setters, or serializability. Implementing deep cloning using the first two approaches can be very coding intensive. The last approach tends to be significantly more expensive, but it is the easiest way to give you a deep copy of a complex data structure ... if that's what you need.
... but I am doing this in applet so can't serialize the object due to restriction on applet to access the file system.
Java object serialization (using ObjectOutputStream
and ObjectInputStream
) and XStream can both write objects to streams that are backed by in-memory buffers; e.g. ByteArrayOutputStream
. This avoids the need to access the file system ... and will be faster.
Well, one alternative is to provide a copy constructor, and honestly, given the extralinguistic nature of Java's clone implementation I tend to prefer this option.
The copy constructor consists of a constructor that receives, as it single parameter, another instance of its same type. Then you go field by field doing the corresponding copying.
When you do this kind of thing, you must take immutability into account to avoid problems.
Another approach is to serialize your object, and then deserialize it, but this implies that you would need to implement Serializable, which is not always an option and it is not free of certain implications.
精彩评论