I like to have a java.util.Map, which holds different generic class objects. In my case handlers such as this:
public interface Handler<s>{
public void encode (S data, OutputStream out);
public S decode (InputStream in, long length);
}
I have implementing classes such as:
public class SpecializedHandler implements Handler<FirstSpecialItem>{
public void encode (SpecialItem data, OutputStream out){
// do something
}
public SpecialItem decode(InputStream in, long length){
// do something
}
}
and another class which implements Handler.
For FirstSpecialItem and SecondSpecialItem exists a parent class AbstractSpecialItem.
Because I had a lot of problems using encode and decode already, I ended up with the following map, which enables to use of decode and encode as follows:
Map<Long, Handler<? super AbstractSpecialItem>> handlers;
// I can use it as follows
AbstractSpecialItem item = new FirstSpecializedItem();
handlers.get(1L).encode(item,System.out);
AbstractSpecialItem returnVal = handlers.get(1L).decode(System.in, 100L);
However, I can't create the map by adding different Handler implementations such as:
SpecializedHandler a = new SpecializedHandler();
SpecializedSecondHandler b = new SpecializedSecondHandler();
Map<Long, Handler<? super AbstractSpecialItem>> handlers = new HashMap<Long,Handler<? super AbstractSpecialItem>>();
handlers.put(0L, a); // does not work
handlers.put(1L, b); // does not work
Eclipse always says these values are not applicable to the Map. I think this behaviour is valid and tried to understand Generics and the PECS principle better (looked through the web and some books). But I still don't get it, to figure out a solution. Where I have the Handler classes with their special generic types and be able to use the methods (encode,decode) as well as create an Map of Handlers.