次のコードを使用して、抽象型 (動物) のリストから、指定されたクラス (犬、猫) に最初に一致する要素を取得しています。それを行う別のタイプセーフな方法はありますか?
// get the first matching animal from a list
public <T extends Animal>T get(Class<T> type) {
// get the animals somehow
List<Animal> animals = getList();
for(Animal animal : animals) {
if(type.isInstance(animal)) {
// this casting is safe
return (T)animal;
}
}
// if not found
return null;
}
// both Cat and Dog extends Animal
public void test() {
Dog dog = get(Dog.class); // ok
Cat cat = get(Dog.class); // ok, expected compiler error
}
(猫と犬は動物を拡張します)