I have a socket class which receives packages (byte arrays). Every package has an integer in order to identify its type. Every case in the switch statement looks like this:
switch(packet.getHeader().getID()) {
case PingRequest.ID:
if(data.length != PingRequest.SIZE)
return null;
PingRequest pingRequest = new PingRequest(data); /* specific parsing of the byte array */
pingRequest.setHeader(data); /* method of the abstract class */
packet = pingRequest;
break;
case Error.ID:
if(data.length != Error.SIZE)
return null;
Error error = new Error(data);
error.setHeader(data);
packet = error;
break;
...
Every packet has different information which is why every packet has a different constructor (creates the packet members from the byte array data
)
Since every case looks somewhat similar (and there are a lot of them) I thought I should optimize it by using a HashMap:
public static HashMap<Integer, Class<?>> _packetTypes = new HashMap<Integer, Class<?>>();
_packetTypes.put(PingRequest.ID, PingRequest.class);
What I now wanted to achieve was something like this:
Class<?> myClass = PacketAbstract._packetTypes.get(packet.getHeader().getID());
Class[] cArg = new Class[1];
cArg[0] = Byte.class;
Constructor<?> ct = myClass.getConstructor(cArg);
/* Doesn't make any sense from here on */
myClass specialPacket = ct.newInstance(data);
specialPacket.setHeader(data);
packet = specialPacket;
So the basic idea was to create a hashmap which contains the packet id and the corresponding packet class which would allow me to create the specialized packet. The last code section was meant to replace my switch statement.
Question:
Is my idea how to solve this correct? If not please enlighten me. How do I implement the last part of my code which doesn't make sense so far (if this is the right way to go)?
EDIT: packet is an object of the abstract class Packet
which gets extended by every special packet like PingRequest