2

我正在使用以下代码从抽象类型(动物)列表中获取与给定类(狗、猫)的第一个匹配元素。有另一种安全的方法吗?

// 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
}

(猫和狗延伸动物)

4

3 回答 3

3

代码看起来正确。这一行:

Cat cat = get(Dog.class);

确实不应该编译。

我会确保您没有在代码中的任何地方使用原始类型,因为这通常会“选择退出”看似无关代码的泛型。

于 2013-01-18T13:45:25.883 回答
3

我的代码出现编译器错误:

public void test() {
    Dog dog = get(Dog.class); // ok
    Cat cat = get(Dog.class); // compiler error
}

我只能看到一种可以编译的情况:

class Dog extends Cat {
}
于 2013-01-18T13:48:08.210 回答
2

我会在你的代码中改变一件事。代替

return (T)animal;

我会用

return type.cast(animal);

后者不会生成未经检查的强制转换警告。

于 2013-01-18T19:34:58.433 回答