问题
Lets say I have a class named Dog which is a subclass of Animal
I have a method that needs to create an instance of a specific subclass of animal based on a string parameter
public void createAnimalType(String animalType) {
Class clazz = Class.forName(animalType);
//Check if animalType equals Dog, or Cat, or Fox, etc
// Example
Dog dog = (Dog) clazz.newInstance();
...
Is there a way to crate an instance of itself (Dog, Cat, etc, Not of type Animal) without using an explicit cast to the Subclass (Dog)in this case?
I may be missing a finer point of polymorphism (as in why do I want to do that . . should be casting it to Object or Anmial :-) )
Thanks for helping me get smart on this.
回答1:
If there is a no-args contructor, you can use getClass().newInstance().
getClass() when used in a superclass will give you the actual class of this, for example Dog in your example.
Your whole method would become:
public Animal createAnimal() {
return getClass().newInstance();
}
来源:https://stackoverflow.com/questions/10258245/java-using-class-forname-to-dynamically-get-a-new-instance-of-itself