嘿家伙我坚持一个问题.说我有一个界面动物.然后我有实现它的类,如Dog,Cat,Goat.假设每个类都有一个从接口获得的update()函数.
我有一个动物的arraylist,包括所有不同种类的动物类(狗,猫,山羊).如果给我一个字符串说"山羊",我将如何搜索该arraylist并仅选择Goat update()函数,忽略Dog和Cat ...
for ( Animal a : animals ) {
if ( a instanceof Goat ) {
a.update();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你真的只有String"Goat"继续下去,你可以这样做:
if ( a.getClass().getName().endsWith("Goat") ) {
//...
Run Code Online (Sandbox Code Playgroud)
或者,如果String与类的名称无关,则可以将String映射到Class的实例:
Map<String, Class<? extends Animal>> map = new HashMap...
map.put("Goat", Goat.class);
//...
if ( map.get("Goat").isInstance(a) ) {
a.update();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,谷歌的番石榴是最好的选择:
for ( Goat g : Iterables.filter(animals, Goat.class) ) {
g.update();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |