具体来说,我有一个对象列表。该类对象的每个子类都与特定的功能相关联。
这是我对这个问题的天真解决方案,而且很丑:
List<SuperClass> superClasses = ...
List<Subclass1> obj1 = Lists.newArrayList();
List<Subclass1> obj2 = Lists.newArrayList();
List<Subclass1> obj3 = Lists.newArrayList();
List<Subclass1> obj4 = Lists.newArrayList();
...
for (SuperClass obj : superClasses) {
if (obj.getClass().equals(Subclass1.class)) {
obj1.add((Subclass1) obj);
}
}
//repeat for each subclass
我也尝试过这样的事情:
public Map<Class, List<SuperClass>> constructMap(List<SuperClass> superClasses);
但这不能用:
(List<Subclass1>) constructMap(superClasses).get(Subclass1.class)
cannot cast from List<SuperClass> to List<Subclass1>.
我注定要在这里使用幼稚的代码吗?真的没有聪明的方法来获取超类对象的列表并根据它们的实际类来处理它们吗?
这是我要解决的问题:
public Driver {
List<Fruit> fruits = collectAllFruit();
StemHandler.pullStem(fruitsThatAreApples, fruitsThatArePears);
ColorHandler.getColor(fruitsThatAreApples, fruitsThatAreOranges, fruitsThatArePears);
public interface Fruit {
getColor();
}
public class Apple implements Fruit {
getColor();
pullStem();
}
public class Orange implements Fruit {
getColor();
peel();
}
public class Pear implements Fruit {
getColor();
pullStem();
}
public interface FruitHandler {
}
public class StemHandler extends FruitHandler {
pullStem(List<Apple>, List<Pear>)
}
public class ColorHandler extends FruitHandler {
getColor(List<Apple>, List<Orange>, List<Pear>)
}