File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes java.lang.ClassCastException: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.lang.ClassCastException: " Watch "java.lang.ClassCastException: " New topic


Maha Hassan
Ranch Hand

Joined: Aug 02, 2005
Posts: 133
Dear All,
i have the following program to do an xpath query , when i run it i get the following error ..anyidea why??


thanks a lot
Adam Nace
Ranch Hand

Joined: Jul 17, 2006
Posts: 117
Apparently, you are attempting to cast an object to a type that it does not belong to. I'm not sure which line is causing the exception, since you didn't provide the stack trace or line numbers, but I'm assuming it's the cast to (ListNodeList).

Look, xpath.evaluate will not return an instance of ListNodeList, because you have created that class, so xpath doesn't even know that it exists. It's actually returning a DTMNodeList, which is not a subtype of ListNodeList. So you cannot cast DTMNodeList as a ListNodeList. If you want to convert from one to the other, you will have to create a method that will do the conversion.

To do this, you will need to figure out what the "important" members of DTMNodeList are (the ones that you care about), and extract them from the instance of DTMNodeList and use them to create your ListNodeList. Then you can use the methods you created in your ListNodeList class. (Basically, you wil need to obtain the list of nodes from the DTMNodeList and use it in the constructor of your ListNodeList).

- Adam
Maha Hassan
Ranch Hand

Joined: Aug 02, 2005
Posts: 133
but DTMNodeList is not a part of java ?

and this error comes when running not when compiling so i do not know where it is ??
[ July 18, 2006: Message edited by: Maha Hassan ]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

You are casting the result of xpath.evaluate(...) to your own class ListNodeList. You get the error because the method returns an object of type, which is not a ListNodeList.

Indeed, DTMNodeList is not a part of the standard Java API, but that's not the problem.

The method xpath.evaluate(...) doesn't know your class ListNodeList, so how can it ever return an object of type ListNodeList?

You just have to use org.w3c.dom.NodeList and not your own class ListNodeList:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Maha Hassan
Ranch Hand

Joined: Aug 02, 2005
Posts: 133
thanks a lot it worked
I agree. Here's the link:
subject: java.lang.ClassCastException:
It's not a secret anymore!