简体   繁体   中英

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). 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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