Note: I know i can use APIs, but what i'm trying to do is solving it in a very generic way, because, at runtime i don't know what types I'm casting to, the values of the class types are stored in a map which the runtime picks from and casts to.
SCJP 5.0, SCWCD 1.4, SCJA 1.0
Joined: Feb 25, 2006
AFAIK, Date doesn't have a cast(...) method. Could you post an SSCCE * that demonstrates this behaviour?
What you are trying to do is not a cast. What you are trying to do is a conversion. And there is not generic way to do that.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Take a look at the DateFormat class and it's parse() methods. The parse methods can be used to parse a String into a Date object. Also be sure to look at the setLenient(boolean) method as well.
To do this, you'll need to know you have a String object. So you can either do an "instanceof" check to see if it is a String, or just call the toString() method on whatever object you have. That will, obviously, return a String representation of the object. If that representation can be parsed, you have your Date object. If not, a ParseException is thrown. That's probably the closest you'll come to a generic way of doing something like this.
If your map can possibly contain a Date object, I would at least use instanceof so you simply use that object rather than go through all the work of converting a Date to a String only to be converted back to a Date.
Another option... if all (or most) of the objects that are going to be put in the map are your own objects, create some interface, such as DateConvertible, with a single toDate() method (that returns a Date). You can then write a custom method for each object type. Use an instanceof check to see if the object is an instance of DateConvertible. If so, cast it to a DateConvertible and then call the toDate() method. If not, use the toString methodology from above. That will hopefully cover most cases for you.
Another idea is to use a type of Strategy pattern. If your Map is going to be limited to a fixed number of pre-known object types, you can create a convertorfor each type that implements some interface, say "DateConverter". Use a naming convention of "<ClassName>DateConverter" for each converter. Then using the getSimpleClassName, you can create the name of the class you need. Lastly, use one of the forName() methods and the newInstance() method to get an instance of the necessary Converter:
This last idea will of course make your code some what brittle.
Just some ideas to get you started. [ August 17, 2008: Message edited by: Mark Vedder ]