This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Abhishek Nigam
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It sounds like the true runtime type of your object is not java.util.Date.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic