[jdom-interest] clone() and subclassing
Ken Rune Helland
kenh at csc.no
Thu Mar 1 08:59:14 PST 2001
Hello.
I have a suggjestion about clone()
for example in Element.clone() the first line
shoud be
Element element = (Element) super.clone();
instead of
Element element = new Element(name, namespace);
This way in my subclass i can call
MyElementSubClass element = (MyElementSubClass) super.clone();
and get a MyElementSubClass object where all the Element stuff
is already set correctly and only care about my added stuff.
This shoud also apply to the other classes.
Object.clone() makes a byte for byte copy so
you will only need to care about references to
mutable objects
( clone.foobar = (this.foobar == null)?null:(Foobar) this.foobar.clone() );
My suggjesgstion for Element.clone():
/**
* <p>
* This returns a deep clone of this element.
* The new element is detached from its parent, and getParent()
* on the clone will return null.
* </p>
*
* @return the clone of this element
*/
public Object clone() {
Element element = (Element) super.clone(); // will return an
Element
// or a supclass of Element
// no need to worry anbout name and namespace
// they are imutable and the references will be
// copied by Object.clone
// these must be set to null because they
// are copied by Object.clone() and the clone is not to belong to a
// document or parent yet;
element.parent == null;
element.Document == null;
// the clone also has references to the originals list
// so this must be set to null befor we add the cloned
// content (new lists will be created by the add metods)
element.attributes = null;
element.content = null;
element.additionalNamespaces = null;
if (attributes != null) {
// List list = new LinkedList(); // i did not se the point of
this line
for (Iterator i = attributes.iterator(); i.hasNext(); ) {
element.addAttribute((Attribute)((Attribute)i.next()).clone());
}
}
if (content != null) {
for (Iterator i = content.iterator(); i.hasNext(); ) {
Object obj = i.next();
if (obj instanceof String) {
element.addContent((String)obj);
} else if (obj instanceof Comment) {
element.addContent((Comment)((Comment)obj).clone());
} else if (obj instanceof Entity) {
element.addContent((Entity)((Entity)obj).clone());
} else if (obj instanceof Element) {
element.addContent((Element)((Element)obj).clone());
} else if (obj instanceof CDATA) {
element.addContent((CDATA)((CDATA)obj).clone());
}
}
}
I think this could also be done on the other clonable classes.
Am i missing somting that would invalidate my reasoning?
Best Regards
KenR
More information about the jdom-interest
mailing list