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?
The Billboard Hot 100 - 08 Jun 2007 12:10 GMT
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
Tom Hawtin - 08 Jun 2007 13:25 GMT
> 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<
Class<? extends Annotation>, Handler<? extends Annotation>
> map = new java.util.HashMap<
Class<? extends Annotation>, Handler<? extends Annotation>
>();
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.)