Re: How to cast a String to an object reference?
Shawn wrote:
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?
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"));
}
}