很难找到这个问题,因为我不完全确定如何定义它。请多多包涵。
最好的问题是:在 Java 中,如何创建其类在运行时通过多态定义而不是在代码中预定义的变量?
也许我可以通过示例来最好地定义这一点:假设我有一个抽象超类 Superhero,其子类是 Thug、Psionic、Shooter 和 Gadgeteer。我想从一个 CSV 数据文件中读取其行条目是单个超级英雄;在文件为每个超级英雄列出的变量中,他们属于哪个类。然后如何将每个超级英雄分配给文件中列出的类?到目前为止,我所做的包括以下内容。
我创建了一个子类类型数组,如下所示:
numberOfClasses = 4; // constant
Superhero[] heroType = new Superhero[numberOfClasses];
heroType[0] = new Thug();
heroType[1] = new Psionic();
heroType[2] = new Shooter();
heroType[3] = new Gadgeteer();
然后我们有一个遍历文件每一行的 for 循环。对于每一行,它将英雄的名字读入变量 tempClassName,然后开始一个嵌套循环,执行此操作:
for (int index=0; index<numberOfClasses; index++)
{
Class heroClass = heroType[index].getClass();
if (tempClassName.equals(heroClass.getName()))
{
Superhero newHero = new heroClass; // problem line
}
}
最后一个问题应该创建一个新的 Superhero 对象,其子类是变量 heroClass 中的任何内容。但是您可能会看到这不起作用。将其定义为“new heroClass”会产生语法错误,因为它需要一个方法 heroClass()。但是“new heroClass()”也是一个问题,因为 heroClass 不是一个方法。基本上,我怎样才能使用 getClass() 的结果作为我新创建的变量的(子)类类型?我需要对每个子类中的构造函数做些什么吗?