Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2006

Tip: Looking for answers? Try searching our database.

How to cast a String to an object reference?

Thread view: 
Shawn - 19 Sep 2006 14:54 GMT
Dear All,

I have a Person class already. Now I have a String:

public class Person()
{
    void sayHello()
    {
        System.out.println("Hello");
    }

}

Person goodGuy = new Person();

String str = "goodGuy";

(Person)str.sayHello();  //Error: cannot cast from String to Person

This is desireable or I am just totally out of my mind?
Chris Uppal - 19 Sep 2006 15:01 GMT
> Person goodGuy = new Person();
>
[quoted text clipped - 3 lines]
>
> This is desireable or I am just totally out of my mind?

Er... The latter, I'm afraid.

   -- chris
Robert Klemme - 19 Sep 2006 15:50 GMT
>> Person goodGuy = new Person();
>>
[quoted text clipped - 5 lines]
>
> Er... The latter, I'm afraid.

:-) I was going to say the same.

Shawn, you probably still operate in C++ mode - where such a cast can be
made to work.  (Whether it's reasonable is a completely other
discussion.)  In Java you will have to write an explicit conversion
either with a constructor of Person that accepts a String or via some
(probably static) method that does the job.

Kind regards

    robert


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.