File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes is it possible to cast a string to class or object Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "is it possible to cast a string to class or object" Watch "is it possible to cast a string to class or object" New topic
Author

is it possible to cast a string to class or object

sree dhar
Greenhorn

Joined: Mar 04, 2007
Posts: 4
pls can anyone tell me is it possible to cast a string to class or object?
if so how?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32604
    
    4
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
Sheriff

Joined: Oct 13, 2005
Posts: 32604
    
    4
. . . 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

Joined: Jul 27, 2006
Posts: 131
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

Joined: Aug 31, 2004
Posts: 11343

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.


"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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: is it possible to cast a string to class or object
 
Similar Threads
foreach
casting of an array
doubt in cast
How to typecast an object which is of unknown class type at runtime?
a bit stumped