[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Class casting question
I wonder if your problem might not actually be conceptual, but syntactical
(I am assuming that when you are trying to cast the Super return value of
the function as a Sub type, the reference being passed really is to a Sub
object). If that is the case, it may be that you need the following
instead:
Sub sub = (Sub)(UtilXML.parseXMLSTRING());
Without the additional parentheses, I think the cast may be happening on the
UtilXML object before the method is called, leading to a problem where a
UtilXML reference cannot be cast as a Sub reference. You need to be sure
the method is called, and the cast applied to the return value. The
additional parentheses ought to do the trick. Hope this helps.
Jeff
----- Original Message -----
From: "Tracy McAbee" <tracy.mcabee@visionarysystemsinc.com>
To: <ajug-members@ajug.org>
Sent: Thursday, March 20, 2003 7:13 PM
Subject: Class casting question
> I have a utility class with a method that parses an XML string (and one
that
> parses an XML file) and returns a superclass which holds the parsed
> information. I'd like to use this utility for sub-classes as well,
without
> writing new methods to return each sub-class. Can it be done? I know I
get
> a ClassCastException at runtime when I use::
>
> Sub sub = (Sub)UtilXML.parseXMLSTRING();
>
> which makes sense. There's got to be a better way, but I'm having a hard
> time finding it.
>
> Here's an example of the classes and utility class to which I'm referring:
>
> public class Super (
> // holds parsed values
> )
>
> public class Sub extends Super (
> // sub-class of Super
> )
>
> public class UtilXML {
> public static Super parseXMLFILE(String fileName, String endTag);
> public static Super parseXMLSTRING(String xml, String endTag);
> )
>
> Is there a proper way to deal with this situation? Just trying to see if
> anyone has some ideas...
>
> Thanks.
>
> Tracy McAbee
>
>