一段时间以来,我一直在寻找问题的解决方案,但找不到专门针对我的问题的答案。 我有一个抽象的 A 类和扩展 A 类的 B 类和 C 类。A 和 B 是具体类。 A 类实现将由 V 和 C 继承的函数。在这个函数中我想创建 B 或 C 的新对象 - 问题是我不知道那是哪个对象。
我怎样才能做到这一点?
public void colision(List<Organism> organisms) {
List<Organism> temp = new ArrayList<Organism>(organisms);
temp.remove(this);
for (Organizm organism : temp){
if (this.location == organizm.getLocation()){
if (this.getClass().equals(organism.getClass())){
//here is what I need to figure out
}
else{
...
}
}
}
}
}
最佳答案
使用 Class<T>.newInstance()
例如。:
organism.getClass().newInstance()
.
为此,您需要在类定义中包含默认构造函数,否则您需要查找构造函数 - 例如:
Constructor constructor = organism.getClass().getDeclaredConstructor(parameterTypes...);
然后像constructor.newInstance(arguments...);
一样使用它.
关于java - 创建未知类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153309/