Imagine you have a web socket you are reading from, that could have messages of many different types (100+). In Java, I would think the ideal way of processing these messages is to first map each message from its String
value to its correct Java POJO (with some object-mapper like jackson
), then handling the message accordingly.
Additionally (in my scenario), each message is guaranteed to contain a type
field that indicates the type of message it is (i.e., the Java POJO it should be mapped to).
Assuming all POJOs have already been defined that all extend some Message
super-class that has the type
field, how would you go about performing this mapping?
One approach is to write the following:
public class Message {
private String type;
// getters & setters
}
public class Obj1 extends Message {
// fields, getters, & setters
}
// ... Many other POJOs
// Imagine this is a Jetty WebSocket or something like that
public class WebSocket {
// Assume this is the generic message handler the web socket sends incoming messages to
public void onMessage(String message) {
ObjectMapper mapper = new ObjectMapper();
Message mappedMessage = mapper.readValue(Message.class, message);
if (mappedMessage.getType().equals("Obj1")) {
Obj1 obj1 = mapper.readValue(Obj1.class, message);
// process obj1
else if (mappedMessage.getType().equals("Obj2")) {
Obj2 obj2 = mapper.readValue(Obj2.class, message);
// process obj2
else if (mappedMessage.getType().equals("Obj3")) {
Obj1 obj3 = mapper.readValue(Obj3.class, message);
// process obj3
}
// 100+ more else ifs
}
}
I know this could be done with a massive switch statement as well, but I'm more looking for a way to not write 100 case
/else if
statements.
Is there some sort of way to use Reflection
or a design pattern that could be used here, or is this simply the way in which one maps messages from a web socket into Java POJOs?