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();
java.lang.Class. Pay particular attention to thenewInstancemethod: docs.oracle.com/javase/6/docs/api/java/lang/Class.html