Can type of instantiated object depend DIRECTLY on a String?
Posted on 2007-03-28
I know in advance that my project contains classes named Bob and Alice.
Is is possible to construct a factory method such that I pass in a literal String "Bob" or "Alice" and have it return an Object of type Bob or Alice?
So it would be:
Object someObject = getObjectBasedOnName("Bob");
and someObject would be of type Bob.
But the method getObjectBasedOnName CANNOT directly know what classes it's supposed to create. It can't have a statement that says:
return new Bob();
return new Alice();
Instead, it has to magically make a new object based DIRECTLY on the name, like:
return new <<someMagicalStringToObjectTechniqueGoesHere...>>();
(BTW, I know the answer is probably, No, stupid. Thought I would ask...)