I am aware of Oracle tutorials and questions like How do I make the method return type generic? but still I am having trouble returning generic objects from a Java method.
Brief example: I have a hierarchy of network Packet
s and a hierarchy of Handler
s, parametrized to the Packet
they handle. Eventually I have a registry of Handler
s which includes a method to that would return me the proper handler of a given packet.
I would like to implement all of this with ideally no warning to manually suppress.
class Packet {}
class ThisPacket extends Packet {}
class ThatPacket extends Packet {}
interface PacketHandler<P extends Packet> {
boolean handle(P p);
}
class ThisPacketHandler extends PacketHandler<ThisPacket> {
boolean handle(ThisPacket p);
}
class ThatPacketHandler extends PacketHandler<ThatPacket> {
boolean handle(ThatPacket p);
}
This is quite regular I believe, in my implementation I have some further abstract classes in the middle to shape my hierarchy, but I think this can be ignored by now.
The critical part is i) the registry:
class HandlersRegistry {
static <<RETURN TYPE>> getHandler(Packet p) {
if (p instanceof ThisPacket) return new ThisPacketHandler();
if (p instanceof ThatPacket) return new ThatPacketHandler();
return null;
}
}
<<RETURN TYPE>> OPTIONS (I tried):
// Raw-type Warning:
A. PacketHandler
// the registry user won't be able to use the handler:
B. PacketHandler<? extends Packet>
// Type mismatch: cannot convert from
C. PacketHandler<Packet>
..and ii) and the registry user:
class HandlerSwitchExample {
public static void main() {
// [...]
<<OBJECT TYPE>> handler = HandlersRegistry.getHandler(somePacket);
handler.handle(somePacket);
}
}
Hope the example is fairly clear. Thanks for any helpful suggestion, even complete redesign strategies.
PacketHandler
getHandler( P p)` work?
– biziclop Mar 18 '15 at 10:43`.
– Campa Mar 18 '15 at 10:57