I am currently trying to rework some code on our server that is super non-pretty Java hard-coded mess. The server receives a byte opcode from the user, and then some variable amount of size. The server will then process this information by reading whatever packet type is at the opcode, stored in a large array. Below is what this looks like:
class Type {
private static Type[] ids = new Type[256];
static {
type[0] = new SomeType();
type[1] = new Another();
type[2] = new SomeType4();
// 254 more entries . . .
}
}
I am trying to look for a more automated approach to this. My first idea would be to create an abstract class PacketType
that contained a public static final List<PacketType> packets
. Then, in each implementing class in a static
initializer, it will add the instance of itself onto the list. There is two problems with that solution however:
- The same class initialization code will need to be "copy-pasted" into every implementing class.
- The classes will be added to the list in an unpredictable order. The client will not know which packet serves as which byte code.
Another solution that I contemplated was having a PacketKeeper
class that has a Map<Byte, Class<? extends PacketType>>
and a parallel Map<Class<? extends PacketType>, Byte>
. Surely there must be a better, more beautiful solution to this problem I am having in Java semantics. What is the best way to refactor this long chain of intializers?