Can type of instantiated object depend DIRECTLY on a String?

Dear Experts,

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:

if (parameter.equals("Bob"))
  return new Bob();
else (parameter.equals("Alice"))
  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...)

Who is Participating?
elfe69Connect With a Mentor Commented:
If you have the fully qualified name of a class, including the package name, you can create a new instance of the class with Class.forName("myClassName").newInstance(), for example if your Bob and Alice classes are in a package named my.persons, you could write a method like this:

public final static Object createObject(String classname) throws Exception {
  return Class.forName(classname).newInstance();
VoxSisConnect With a Mentor Commented:
I don't know to answer directly to your question but you should read about ClassLoader at
and see if it can be in any help.

... and you will be able call that method the following way:

// obtain an object of Bob type
Object myRuntimeObject = createObject("my.persons.Bob");
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

BrianMc1958Author Commented:
To elfe69:
>>If you have the fully qualified name of a class, including the package name
Does "fully qualified" mean "location on the disk drive"?  Like "C:\MyDir\my.persons.Bob"?
No, it means the package name of your class, like "experts.persons" in the following source file:

package experts.persons;

public class Bob {
      public String getName() {
            return "Hello, this is Bob";

You could create an object of the Bob class this way:

Object myRuntimeObject = createObject("experts.persons.Bob");
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
Yes, you need to use reflection for this. Have a look at the explanation I'd given here for a similar scenario (that was related to data-stores):
BrianMc1958Author Commented:
Well, you folks have given me exactly what I asked for.  Thanks again...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.