3

In JAVA, say I have a string variable:

String x = "CoolClass";

And I have a class called CoolClass with a working constructor. How could I create an object of CoolClass, using the variable x, instead of typing CoolClass itself.

(I need to do this because x will be given by the user and read in by Scanner, and depending on their input, a different object/class will be constructed accordingly).

1
  • here is a good place to start Commented Jun 4, 2013 at 20:44

4 Answers 4

9
Class.forName(x).newInstance()

would work, though reflection can be tricky and dangerous. Can you tell us what you're actually trying to do?

Sign up to request clarification or add additional context in comments.

2 Comments

Sure Louis! I have different classes for different animals. I ask the user to input one type of animal. I scan their response, and save it as a string. Then, I create an object (animal) of that string. Would your suggestion be "dangerous" for that purpose?
I would generally prefer to have an explicit list, or even better, a Map<String, AnimalFactory>. This'll work, though.
6

This task requires reflection -- Class.forName(x).newInstance().
You might want to use a different design method. Why is the user typing in the desired class?

2 Comments

It is a simulation of a zoo, and they create different animals for different cages. It is a game, nothing serious :o)
@StellaJ A better design pattern might be to use an overarching Animal class, then have the user input the type and store it as a local variable. Creating different classes for different animals seems like overkill, especially since you'll need to call the same methods on all of them.
3
Scanner kbReader = new Scanner(System.In)
String animalType = kbReader.nextLine();

Animal animal; //assume that Lion, Tiger, and Bear inherit Animal

if(animalType.equals("Lion")
{
   animal = new Lion();
}

else if(animalType.equals("Tiger")
{
   animal = new Tiger();
}

else if(animalType.equals("Bear")
{
   animal = new Bear();
}

This is without using reflection of any sort.

1 Comment

Thank you, I might use that to be safe :o)
1

You should use Class.forName(x).newInstance() if your class has default constructor. If the constructor is expected to receive parameters use Class.forName(x).getConstructor(YOUR PARAMETER TYPES).newInstance(YOUR ARGUMENTS)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.