类型安全返回泛型子类的Java方法

时间:2013-01-18 13:37:04

标签: java generics subclass

我正在使用以下代码从抽象类型(Animal)列表中获取具有给定类(Dog,Cat)的第一个匹配元素。还有其他类型的安全方法吗?

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

(猫与狗延伸动物)

3 个答案:

答案 0 :(得分:3)

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

Cat cat = get(Dog.class);

Indeed should not compile.

我会确保你没有在代码中的任何地方使用rawtypes,因为这通常会“选择退出”看似不相关代码的泛型。

答案 1 :(得分:3)

我的代码出现编译错误:

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

我只能看到一个可编译的案例:

class Dog extends Cat {
}

答案 2 :(得分:2)

我会在你的代码中改变一件事。而不是

return (T)animal;

我会用

return type.cast(animal);

后者不会生成未经检查的投射警告。