Monday, April 16, 2007

Still having trouble with ClassCastException?


Photo Sharing and Video Hosting at Photobucket
ClassCastException is still the most common search term that sends people to this blog, although "swim across the atlantic ocean" is about to overtake it thanks, I can only guess, to fans of Detroit Roller Derby (don't ask ...).

So to be helpful to those readers who are not from Michigan I thought I'd clarify things as much as I can, be warned though it isn't much.

Because Sun's spec doesn't enforce a requirement for ClassCastExceptions to show the classes of the objects which you are trying to cast (see this earlier post) it is normally only possible to make any sense of a ClassCastException by reading the source code, and you really need to attach a debugger and examine the object that your programme is trying to cast before you can start to figure out why it won't work.

If your object seems to be of the correct class the problem is probably related to ClassLoaders, this article explains succinctly why that happens.

Sometimes, if you're smart, you can make a smart guess.

Sometimes (more often if programmers will take my advice) the exception message will tell you, but don't count on it.


If you are seeing a ClassCastException being thrown by a product you have installed then you need to check its documentation.

If the documentation doesn't help then you need to get help from the people who wrote it.


Comments:

blog comments powered by Disqus

I know nothing, I'm not a fortune teller, and you'd be insane to think that I am. This disclaimer was cribbed from an email footer I once received. It is so ridiculous I had to have it for myself.

Statements in this blog that are not purely historical are forward-looking statements including, without limitation, statements regarding my expectations, objectives, anticipations, plans, hopes, beliefs, intentions or strategies regarding the future. Factors that could cause actual results to differ materially from the forward looking statements include risks and uncertainties such as any unforeseen event or any unforeseen system failures, and other risks. It is important to note that actual outcomes could differ materially from those in such forward-looking statements.

Danny Angus Copyright © 2006-2013 (OMG that's seven years of this nonsense)