How do I return to generic type in the method?

Asked 1 years ago, Updated 1 years ago, 122 views

If you look at the same example below in the OOP book,

If you have an Animal class, each animal has several friends. And the subclasses are Dog, Duck, Mouse, etc. Each of them makes a bark(), a quack().

public class Animal {
    private Map<String,Animal> friends = new HashMap<>();

    public void addFriend(String name, Animal animal){
        friends.put(name,animal);
    }

    public Animal callFriend(String name){
        return friends.get(name);
    }
}

There's a code like this.

Mouse jerry = new Mouse();
jerry.addFriend("spike", new Dog());
jerry.addFriend("quacker", new Duck());

((Dog) jerry.callFriend("spike")).bark();
((Duck) jerry.callFriend("quacker")).quack();

The above code can be used by using casting operations like this, but what I want is

jerry.callFriend("spike").bark();
jerry.callFriend("quacker").quack();

I'm asking if you can change the return type to a generic type without casting operations.

public<T extends Animal> T callFriend(String name, T unusedTypeObj){
    return (T)friends.get(name);        
}

Like this. Can't I return the generic type like above without using instanceof?

java generics return-value

2022-09-22 22:26

1 Answers

You can define callFriend in this way.

public <T extends Animal> T callFriend(String name, Class<T> type) {
    return type.cast(friends.get(name));
}

Then when you call,

jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();

This is how you can invoke it. This code does not generate compiler warnings.


2022-09-22 22:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.