嘿,伙计们,我被一个问题卡住了。假设我有一个动物接口。然后我有实现它的类,比如Dog,Cat,Goat。假设这些类中的每个类都有一个从接口获取的update()函数。
我有一个动物列表,其中包括所有不同种类的动物(狗,猫,山羊)。如果我得到的字符串是" Goat“,我该如何搜索该数组列表并只选择Goat update()函数,而忽略Dog和Cat...
发布于 2011-03-31 21:49:27
for ( Animal a : animals ) {
if ( a instanceof Goat ) {
a.update();
}
}
如果你真的只有字符串"Goat“可以继续,你可以这样做:
if ( a.getClass().getName().endsWith("Goat") ) {
//...
或者,如果字符串与类的名称无关,则可以将字符串映射到class的实例:
Map<String, Class<? extends Animal>> map = new HashMap...
map.put("Goat", Goat.class);
//...
if ( map.get("Goat").isInstance(a) ) {
a.update();
}
在我看来,Google's Guava是最佳选择:
for ( Goat g : Iterables.filter(animals, Goat.class) ) {
g.update();
}
发布于 2011-03-31 21:52:41
public void goatUpdate(List<Animal> animals) {
for (Animal animal : animals) {
if (animal instanceof Goat) {
animal.update();
}
}
}
发布于 2011-03-31 21:50:28
恐怕您需要仔细查看列表,询问每个对象的类型。如果你有List<Animal>
,(据我所知)没有一种简单的方法可以只获取它的特定子类。
https://stackoverflow.com/questions/5500889
复制相似问题