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:58 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?
Jeffrey Schwab - 19 Sep 2006 15:42 GMT
> Dear All,
>
[quoted text clipped - 16 lines]
>
> This is desireable or I am just totally out of my mind?

If you're calling a method that really doesn't depend on the underlying
object, just make the method static and don't bother with the object at
all:  Person.sayHello().

If the method might depend on the object, you have to get an object of
the right type.  You can't just cast any object to any type; i.e., there
is no Java equivalent of C-style casts, or of C++ reinterpret_cast.

Chances are good that if you feel the need to add new methods to
existing objects, you can get what you want by wrapping the objects in a
new type.  This also has the advantage that when you no longer need the
extra functionality, you can unwrap the objects, so the extra complexity
is limited to (e.g.) the parsing stage of your compiler, or the
loadUserPreferences step of your application, or whatever.  For example,
if you feel the need to call a Person method on a String, try making
Person an interface, and move the functionality into a wrapper class
that knows about Strings.

public interface Person {
    public void sayHello();
}

public class PersonableWrapper<T> implements Person {

    private T wrappedObject;

    public PersonableWrapper(T objectToWrap) {
        this.wrappedObject = objectToWrap;
    }

    public void sayHello() {
        System.out.println(wrappedObject.toString() + ":  Hello!");
    }
}

public class Main {

    private static void workWithPerson(Person person) {
        person.sayHello();
    }

    public static void main(String[] args){

        Integer i = new Integer(42);
        String s = "six times nine";

        workWithPerson(new PersonableWrapper<Integer>(i));
        workWithPerson(new PersonableWrapper<String>(s));
        workWithPerson(new PersonableWrapper<String>("goodGuy"));
    }
}
Oliver Wong - 19 Sep 2006 16:17 GMT
> Dear All,
>
[quoted text clipped - 16 lines]
>
> This is desireable or I am just totally out of my mind?

   It is desirable that the above attempt at casting generate a
compile-time error. Given that Person and String are not related via
inheritance, there is no way for this cast to succeed, and rather let you
find out at runtime, the compiler is able to detect this and tell you so at
compile time.

   - Oliver
Shawn - 19 Sep 2006 16:42 GMT
Thank you all. What I really need is:

public interface Person()
{
    public void saySomething();
}

Person goodGuy = new Person(){
    public void saySomething() {
        System.out.println("How are you?);
    }
};

Person badGuy  = new Person() {
    public void saySomething() {
        System.out.println("I am a bad guy");
    }
};

String str;

//in the middle of my program, str gets a value(goodGuy, badGuy etc). If
the value is "goodGuy", "How are you?" was printed out; if the value is
"badGuy", something else was printed out.

I could use if ... else if ... to do the job. But if there are 10
instances of interface Person(now str can be assigned 10 possible
values), if block will be very long.

I am seeking a better way to do this job.

Thank you again for all your help. I greatly appreciate it.
Robert Klemme - 19 Sep 2006 16:45 GMT
> Thank you all. What I really need is:
>
[quoted text clipped - 26 lines]
>
> I am seeking a better way to do this job.

Use a Map.

    robert
Shawn - 19 Sep 2006 16:52 GMT
> Use a Map.
>
>     robert

Thank you. Somebody just showed me that. You confirmed/enforced the
approach.
Thomas Weidenfeller - 19 Sep 2006 16:54 GMT
 > //in the middle of my program, str gets a value(goodGuy, badGuy
etc). If
> the value is "goodGuy", "How are you?" was printed out; if the value is
> "badGuy", something else was printed out.
[quoted text clipped - 4 lines]
>
> I am seeking a better way to do this job.

Maybe a Map, maybe a state machine, or whatever. Since you are not
telling us what you want to achieve, why you want to do this, it is
difficult to tell.

Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/



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



©2009 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.