0

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?

Matt
  • 902
  • 7
  • 20
  • There may be more elegant solutions, but the obvious thing would be to simply look up the appropriate class object by name given that it seems that the "type" of your objects and the class names that implement them are one-to-one and the names always match. Check this out to get the proper syntax: https://stackoverflow.com/questions/1438420/how-to-get-a-class-object-from-the-class-name-in-java – CryptoFool Sep 20 '22 at 20:23

0 Answers0