Ingdas Ingdas - 14 days ago 7
Java Question

chain-of-responsibility handler with java generics

I'm using the Chain of Responsibility design-pattern in Java. The chain as a whole represents a request for objects of certain types. Each "Handler" in the chain is responsible to handle the requested units of 1 type.
All requests are handled in essentially the same way so I tried making the "Handler"-class generic.
So in the Handle-class I need a method like this (the handling itself is simplified because it would only obfuscate my problem):

public class Handler<T>{
int required;
Handler<?> next;

public void handle(Object O){
if(o instanceof T){
required --;
}else{
next.handle(o);
}
}
}


The problem is that an instanceof like this is impossible. Because the type T isn't explicitly stored during run time (or that's what I understood during my research on the internet). So my question is: what is the best alternative?

Answer

Implement handlers using generics by using a constructor parameter to define the class the handler supports:

public class Handler<T> {
    private int required;
    private Handler<?> next;
    private Class<? extends T> c;

    public Handler(Class<? extends T> c) {
        this.c = c;
    }

    public void handle(Object o) {
        if (c.isInstance(o)) {
            required--;
        } else {
            next.handle(o);
        }
    }

    // ...
}