简体   繁体   English

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

[英]Java method for type safe return generic subclass

I'm using the following code to get the first matching element with the given class (Dog, Cat) from a list of abstract type (Animal). 我正在使用以下代码从抽象类型(Animal)列表中获取具有给定类(Dog,Cat)的第一个匹配元素。 Is there another type safe way to do it? 还有其他类型的安全方法吗?

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

(Cat and Dog extends Animal) (猫与狗延伸动物)

The code looks correct. 代码看起来正确。 This line: 这一行:

Cat cat = get(Dog.class);

Indeed should not compile. 确实不应该编译。

I would make sure you're not using rawtypes anywhere in your code, as often this will "opt out" of generics for seemingly unrelated code. 我会确保你没有在你的代码中的任何地方使用rawtypes,因为这通常会“选择”出现看似无关的代码的泛型。

I get compiler error with your code: 我的代码出现编译器错误:

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

and I can see only one case when it may compile: 我只能看到一个可编译的案例:

class Dog extends Cat {
}

I would change one thing in your code. 我会在你的代码中改变一件事。 Instead of 代替

return (T)animal;

I would use 我会用

return type.cast(animal);

The latter will not generate unchecked cast warning. 后者不会生成未经检查的投射警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM