Java: Using Class.forName to dynamically get a new

2019-08-08 21:38发布

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条回答
何必那么认真
2楼-- · 2019-08-08 22:07

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();
}
查看更多
登录 后发表回答