[jdom-interest] sub-classing element

Ken Rune Helland kenh at csc.no
Mon Jan 28 06:32:27 PST 2002


> 
> I am trying to sub-class the Element and use my own form as I need to
> write a few operations to act on my node of document

Been therem done that :-)
 
> I have the document read from the file and is stored in doc
> 
> org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder();
> org.jdom.Document doc = builder.build(new java.io.File(myTestFile));
> MyDocument myDoc =  new MyDocument((MyNode)doc.getRootElement.clone
> (),(org.jdom.DocType) doc.getDocType());
> 
> 
> I get a classcast exception while casting the clone of getRootElement
> to MyNode.  Is this wrong ..

You misunderstand what the cast does. If you have two classes A and B
and B is a subclass of A. you can cast a B reference to A and use the B 
object everywhere you can use an A object. But not the other way around.

If you have an A reference you can only cast it to B if it is actualy a
B object that is referenced ( you can test this with the instanceof 
operator).

> MyDocument is sub-class of Document and MyNode is Subclass of Element
> 
> 
> The objectinves i need to achieve
> 
>  use my own version of Document and Element so that I can write my owl
> opearions to act upon the document and elements
> 
> thanks
> jasmeet

So you problem is that you try to cast Document and Element objects to
MyDocument and MyNode when they are in fact not.

What you need to to is to subclass the JDOMDefaultFactory to 
produse MyDocument and MyNode objects and give the factory to the 
builder before building. 

Then the cast will work because behind the Document and Element
references there will actually be MyDocument and MyNode objects.
 

KenR





More information about the jdom-interest mailing list