Using Generics to retrieve a list of classes of type Generic
I'm relatively new to generics in Java, so I apologize if this is something common that gets taught in schools (I'm pretty much self-taught). Let's say I have the interface and abstract class below
public interface IChallenge<T> {
boolean handle(T e);
Class<? extends T> getType();
}
public abstract class AbstractChallenge<T> implements IChallenge<T> {
protected Class<T> clazz;
@Override
public Class<? extends T> getType() {
return this.clazz;
}
}
For every class that extends AbstractChallenge, the handle
method takes in the parameter that is specified for the generic. So if I had an event class that gets triggered when Event
happens, I would have
public class EventChallenge extends AbstractChallenge<Event> {
public EventChallenge() {
super(Event.class);
}
@Override
public boolean handle(Event e) {}
}
My problem comes when I'm trying to pass a specific class to the handle
method. Since the generic can be any class, and there can be multiple challenges with the same type, I have the challenges stored in a map with their type as the key.
private Map<Something, List<AbstractChallenge<Something>> challenges = new HashMap<>();
With the ultimate hope of achieving something along the lines of
List<AbstractChallenge<A>> specificChallenges = this.challenges.get(A.class);
specificChallenges.removeIf(challenge -> challenge.handle(A));
But I'm having a hard time figuring out what goes in the 'Something'. If I put the wildcard ?
symbol, then IntelliJ says that handle
must take in a parameter of the requirement: capture of ? when I pass it class A. The best I've gotten to is to not specify the type for AbstractChallenge
but I'd like a better solution.
Any ideas? Thanks!
from Recent Questions - Stack Overflow https://ift.tt/3rr7SLQ
https://ift.tt/eA8V8J
Comments
Post a Comment