• Post Reply Bookmark Topic Watch Topic
  • New Topic

is it possible to cast a string to class or object  RSS feed

 
sree dhar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pls can anyone tell me is it possible to cast a string to class or object?
if so how?
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By string I presume you mean String. By object I presume you mean Object. It is not necessary to cast upward, since a String already is an Object. Try this bit of useless code:- The getClass() method works because it is already present in Object. It won't work the other way, however. You can't compile:-Not unless you cast it:-
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . not that downward casting is always a good idea. There is the risk of an error and the application will crash with a ClassCastException. Also the concatenation I showed you won't do anything because the return value is lost.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting is for magicians, not programmers.

In Java, casting doesn't actually change objects, ever, or create new ones*.
It just provides you with a different view of the same object. E.g., if I do:

Object o=(Object)"hello"; then I've got an Object view of that string. I now can't ask it how long it is, etc., because Objects don't have length.

String s=(String)o; now I've got a String view of it as well. No new object.

By the way, as all Strings are Objects, you don't need the cast to Object in the first code snippet of this post.

* autoboxing alters that slightly, but not enough to be worth explaining in a beginner forum.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
... There is the risk of an error and the application will crash with a ClassCastException...

Yes. So if you must downcast, you might want to check the type first.

In other words, this situation can be anticipated and possibly handled without using Exceptions.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!