Java: Using Class.forName to dynamically get a new instance of itself

谁说我不能喝 提交于 2020-01-05 04:23:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!