Using generics and annotations to resolve implementation interface


M

Meidos

I have an interface as follows:
interface Handler<A extends Annotation> {
handle(A annotation);
}

I have a single implementation for each type of supported annotation.
The annotations are applied to methods in interfaces, and a dynamic
proxy is used to implement the actual method. In order to determine
which Handler to use for a method, I look at it's annotation, and pick
the handler from a map:

Map<Class<? extends Annotation>, Handler<?>> handlerMap;
handlerMap.put(SomeAnnotation.class, new SomeAnnotationHandler());

The problem is that when I get the Handler from the map, it will be a
Handler of type Handler<? extends Annotation>, and I cannot call
handle() on it because the type is unspecified. How can I solve this?
 
Ad

Advertisements

T

The Billboard Hot 100

Hey there,

public class tester {

Map<Class<? extends Annotation>, Handler<?>> handlerMap = new
HashMap<Class<? extends Annotation>, Handler<?>>();
SomeAnnotation some = new SomeAnnotation();

public void deneme(){
handlerMap.put(SomeAnnotation.class, new SomeAnnotationHandler());
handlerMap.get(SomeAnnotation.class).handle(some);
}
}

I tried to solve ur problem. I hope I am right. In the interface
header you need to specify the generic type of methods.

for example


public interface Handler<A extends Annotation> {
<A extends Annotation> void handle(A anotation);
}

Thanks
 
Ad

Advertisements

T

Tom Hawtin

Meidos said:
interface Handler<A extends Annotation> {
handle(A annotation);
}
Map<Class<? extends Annotation>, Handler<?>> handlerMap;
handlerMap.put(SomeAnnotation.class, new SomeAnnotationHandler());

The problem is that when I get the Handler from the map, it will be a
Handler of type Handler<? extends Annotation>, and I cannot call
handle() on it because the type is unspecified. How can I solve this?

You are going to need an unchecked cast.

class AnnotationHandlerMap {
private final Map<
> map = new java.util.HashMap<

public <A extends Annotation> void put(
Class<A> type, Handler<A> handler
) {
map.put(type, handler);
}

@SuppressWarnings("unchecked")
public <A extends Annotation> Handler<A> get(Class<A> type) {
return (Handler<A>)map.get(type);
}
...
}

(Dislaimer: Not tested or even compiled.)
 

Top