0

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.

1
  • 1
    Show us more code, hard to imagine what you really need. Commented Sep 27, 2016 at 11:23

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.