Len*_*nny 1 java object instanceof
我现在正在寻找解决我问题的方法一段时间,但我找不到一个特定于我的问题的答案.我有一个抽象的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{
...
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用Class<T>.newInstance()例如:
organism.getClass().newInstance().为了做到这一点,你需要在类定义中使用默认构造函数,否则你需要找到构造函数 - 例如:
Constructor constructor = organism.getClass().getDeclaredConstructor(parameterTypes...);然后使用它constructor.newInstance(arguments...);.