Rajarshi basu
Rajarshi basu

Reputation: 352

Using generics to pass class type from method to method

In a game that I am writing currently, I have a list of Collectable objects in my inventory.When I activate one of theses objects , some need another Collectable object to work upon.Now , in my UI , I show all the possible candidate Collectable objects that the original object might work upon.To do this, I check if an object IS-A instanceof an interface.But that interface varies from object to object.This UI is called ItemSelector and is called by the main UI.

I construct the ItemSelector by making the constructor take a class<T> selectionCriteria as a parameter.

<T> ItemSelector(Class<T> selectionCriteria){
     // ... Do work.
}

However, that means that when I create an object of this class, I have to specifically hardcode all the different possible interfaces possible in a switch case statement according to the type of the original object.What I want to do is that have a method in each of the Collectable object (the Collectable interface will have a getSelectionCriteriaInterface() method that will be overriden by the concrete classes) that will return the interface it uses as the selectionCriteria.

How do I achieve this. Hoping for a speedy reply, Thanks.

Upvotes: 0

Views: 55

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33845

Like this:

interface Collectable {
    ...
    Class<?> getSelectionCriteriaInterface();
}

Possible implemention:

public Class<?> getSelectionCriteriaInterface() {
    return MyInterface.class;
}

Then when checking, something like:

Collection<Collectable> allItems = ...;
Collectable c = ...;

List<Collectable> filtered = allItems.stream()
    .filter(c.getSelectionCriteriaInterface()::isInstance)
    .collect(Collectors.toList());

Upvotes: 1

Related Questions