How do I instantiate an object using the Class class?
I would like to pass a Class object to a function and have that function return a new object of the class I pass in.
I will be doing casting after I get the object back. Also, are there any suggestions on design patterns for this sort of thing?
Here is some example pseudo code that shows what I want to do:
Class Animal {
String name;
}
Class Cat extends Animal {
boolean hasTail;
}
MAIN:
Class myClass = Cat.class;
Animal createAnimal(myClass) {
return new myClass;
}
Edit:
Also, is there a way to cast within my function before returning the new instance or am I stuck with the default Object type?
return (myClass)myClass.newInstance();
You don’t need to do casting if you take advantage of generics. Generics are described in relatively introductory detail here
Here is a java example derived from your psuedo code using generics and reflection:
As for patterns, any of the typical creational patterns should be looked at when you want to abstract away the creation of objects. The simplest is probably just using a factory method. The example I have above is just a general purpose factory method that doesn’t really gain you much. Here is a pretty short list of patterns you should look up: