Okay, so I am trying to do my network packet handling in Java using classes. For reading data from my stream I use a DataInputStream. My reading thread for my server looks like this:
public void run()
{
while(client.isActive())
{
try{
handle(is.readShort());
}catch (IOException e){
client.stop(e);
break;
}
}
}
Now I’ve got a method handle:
public void handle(short id) throws IOException
{
InPacket packet = null;
try {
packet = ClassUtils.newInstance(InPacket.class, "server.client.InPacket"+id);
}catch (Exception e){
e.printStackTrace();
}
if (packet!=null){
packet.handle(this);
}
else{
throw new IOException("Invalid packet");
}
}
I try to instantiate a new class using the
packet = ClassUtils.newInstance(InPacket.class, "server.client.InPacket"+id);
line.
In ClassUtils this is that function:
public static <T> T newInstance(Class<? extends T> type, String className) throws
ClassNotFoundException,
InstantiationException,
IllegalAccessException {
Class<?> clazz = Class.forName(className);
Class<? extends T> targetClass = clazz.asSubclass(type);
T result = targetClass.newInstance();
return result;
}
My problem is: when I try to get that class with only part of the name (I try to get it by “InPacket1”, while the class is called “InPacket1Connect”), it can’t find it. Is it possible to do this in Java, and if so how? If not, what method do you recommend for handling my network packets?
An alternative approach would be to use a map (or enum) which maps the id to the full class name.
Pulling in the stuff from the comments, ensure that this mapping class is available as a jar (or may be in the same jar which contains the implementations of the packet handlers) as your “messaging layer” jar.