How to cast a String to an object reference?

S

Shawn

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?
 
C

Chris Uppal

Shawn said:
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?

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

-- chris
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,079
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top