Let's say I have two different classes that declare objects: class Cat and class Dog. They are both objects.
Now in my main class, I want to take in a String value (either "Dog" or "Cat"), and create an object of that type. And I'm not looking to have Cases, I'm somehow looking for a dynamic way to create the object.
For example:
public static void main(String [] args){
String object_name = "Dog";
//this is where I want to dynamically create the object
object_name bob = new object_name();
}
And in the case, it would create a Dog object of variable name bob.
Thanks for the help.
Edit##
I used the method:
public static Object generate(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Class<?> c = Class.forName(type);
Constructor<?> ctor = c.getConstructor(String.class);
Object object = ctor.newInstance("9");
return object;
}
Now if I create in main:
Object obj = generate("Dog");
How do I invoke methods in the class Dog? Do I have to cast it as Dog? If I have to cast it, doesn't it lose purpose of generating it through this method? Thanks again.