[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: Class casting question
in the scenario described u can get a classcast if the object returned is an instance of Super and you try to cast it to Sub. use instanceof operator before casting it should help.
-Vikrant
-----Original Message-----
From: Tracy McAbee [mailto:tracy.mcabee@visionarysystemsinc.com]
Sent: Thursday, March 20, 2003 7:13 PM
To: ajug-members@ajug.org
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