开发者

java classcast exception

i have prob开发者_Python百科lems in converting an XML document type into a Document object.. this is the piece of code

Document doc=null;
doc = (Document) parser.parse(sourceFile);

for this line 2 it throws java classcast exception..

without the typecast it shows error as

Type mismatch: cannot convert from org.w3c.dom.Document to javax.swing.text.Document

how do i now typecast properly? any suggestions??


The problem is that there's a collision in the unqualified names.

That is, as a result of your import statements, the unqualified name Document refers to javax.swing.text.Document, but you really need org.w3c.dom.Document instead (that's the type that the parser returns).

You can fix this by using the fully qualified name:

org.w3c.dom.Document doc = (org.w3c.dom.Document) parser.parse(sourceFile);

Or, you can also specifically import the particular Document as follows:

import javax.swing.text.*;
import org.w3c.dom.*;
import org.w3c.dom.Document;

//...

Document doc = (Document) parser.parse(sourceFile);

This is called the single-type import declaration (JLS 7.5.1), and it can be used to "shadow" other declarations.


Those two interfaces have the same name, but are totally unrelated. You cannot cast between them - it doesn't make sense as they represent quite different concepts (OK, theoretically, you could have a Swing component that displays XML trees and uses a DOM Document as its model, but I don't think that's what you have).

What you probably want to do is to take the unparsed XML and call setText(xmlText) on the swing component you want to display it with.


Is your application a Swing application or not?

You are probably using an IDE which you automatically let organize the imports in your source file. The IDE added an import for javax.swing.text.Document instead of org.w3c.dom.Document. This is something I've encountered myself often while using the Eclipse IDE.

What you have to do: Remove this line from the top of your source code file:

import javax.swing.text.Document;

Replace it with:

import org.w3c.dom.Document;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜