aspose file tools*
The moose likes Java in General and the fly likes Converting an object of type 'Object' to type 'java.util.Date' Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Converting an object of type Watch "Converting an object of type New topic
Author

Converting an object of type 'Object' to type 'java.util.Date'

Abhishek Nigam
Greenhorn

Joined: Sep 28, 2007
Posts: 3
Hi all,
When trying to cast 'Object' to 'java.util.Date' ...There's no error at compile time...but gives ClassCastException at runtime...

Thanks,
Abhishek
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

It sounds like the true runtime type of your object is not java.util.Date.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435
    
  23

Casting does not magically convert any kind of object into any kind of other object. A cast is only an indicator for the compiler that says "look, I have some object here, and I know that it's really a java.util.Date, so treat this thing as a java.util.Date". If, at runtime, the object really is not a java.util.Date, you will get a ClassCastException.

If you want to know what the object's real type is, try adding a line like this to your application:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
The point is that you don't cast objects, you cast object references. Java does not even allow variables that are objects.

Casting is for when you know that an object reference actually points to an object whose type is a subclass of the declared type of the object reference. So, if you have an object reference declared to be an Object, but you know that it actually points to an object that is a Date, you can cast the reference to a Date. This has NO effect on the object itself.

If you try to cast an object reference to a class that is not compatible with the object to which it points, you get a ClassCastException. So, if your object reference declared as Object really does point to a plain Object, but you try to cast to Date, you get ClassCastException.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
 
Don't get me started about those stupid light bulbs.
 
subject: Converting an object of type 'Object' to type 'java.util.Date'