In all the previous examples, we have always known what class to read. That is often not the case in real applications. In most of our internal use cases we rarely know what kind of object is being read back or sent over the wire, so we need to be able to:

Consider our initial example (the fruit model). It has three classes:

Suppose we serialize a couple of objects of randomly chosen classes (Apples or Bananas) to a file. Now we want to read them back and see what it was we wrote down. First of all, let’s read the objects back not assuming anything about their types.

In Java (With the reader from the previous java example):

MGenBase object = reader.readObject();

And in c++:

MGenBase * object = reader.readObject(); // read to heap

In Java we can use the following methods to identify the type of the object:

In c++ we can use:

Perhaps the most interesting of these are the Dispatch and Handler types generated by MGen. Handlers are classes with a handle(object) method for every class that you generated code for. Dispatch(ers) are classes or functions that take any MGenBase object reference and a handler, and pass it to the handler’s correct handle(object)-method.

Handlers’ handle(object)-methods have default implementations for all types. The default implementations pass along the object to its base class handler, until the MGenBase class is reached. If no handle(object)-method is overloaded there, the object is ignored.

Here’s a c++ example of using dispatch and a Handler:

// First we define a custom handler class
// that extends the generated Handler class
class MyHandler: public Handler {
public:
  void handle(Apple& apple) {
    std::cout << "That was an apple!" << std::endl;
  }
  void handle(Banana& banana) {
    std::cout << "That was a banana!" << std::endl;
  }
};
    
MyHandler handler;
    
MGenBase * object = reader.readObject();
    
if (object) {
  dispatch(*object, handler);
}

The java way is almost identical. For more information about type identification, dispatch and handlers you can also look in our preliminary technical whitepaper.