可能重复:
这里的 instanceof 检查有什么问题吗?
我有这个代码
public static int getNumberOfOwned(Player owner, String type){
int count = 0;
for (Field f: board.fieldList)
if (type == "Shipping" && f instanceof Shipping)
if (((Shipping)f).getOwnedBy() == owner)
count++;
else if (type == "Brewery" && f instanceof Brewery)
if (((Brewery)f).getOwnedBy() == owner)
count++;
return count;
}
我不认为这是非常优雅和未来的证明。我怎样才能避免那些 instanceof 运算符。