问题描述
假设我有一个名为 Dog 的类,它是 Animal 的子类
我有一个方法需要根据字符串参数创建一个特定的动物子类的实例
public void createAnimalType(String animalType) {Class clazz = Class.forName(animalType);//检查animalType是否等于Dog、Cat、Fox等//例子Dog dog = (Dog) clazz.newInstance();...
在这种情况下,有没有办法在不使用显式转换到子类 (Dog) 的情况下创建自身的实例(Dog、Cat 等,非 Animal 类型)?
我可能遗漏了多态的一个更细微的点(比如我为什么要这样做……应该将其转换为 Object 或 Anmial :-))
感谢您帮助我在这方面变得聪明.
如果有无参数构造器,可以使用 getClass().newInstance()
.
getClass()
在超类中使用时会给你 this
的实际类,例如 Dog
在你的例子中.>
你的整个方法将变成:
public Animal createAnimal() {返回 getClass().newInstance();}
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.
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();
}
这篇关于Java:使用 Class.forName 动态获取自身的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!