Search code examples
javakotlinvert.xjackson-databind

Vert.x 4 eventbus serialize multiple classes with same codec


Is there a way to register a codec for multiple classes? Basically, all my classes should just be serialized using a Jackson object mapper. But it seems like I have to create a custom codec for each class (even though I can abstract it a little bit using generics).

A small code example:

Codec:

class JacksonCodec<T>(private val mapper: ObjectMapper, private val clazz: Class<T>) : MessageCodec<T, T> {
    override fun encodeToWire(buffer: Buffer, s: T) {
        buffer.appendBytes(mapper.writeValueAsBytes(s))
    }

    override fun decodeFromWire(pos: Int, buffer: Buffer): T {
        val length = buffer.getInt(pos)
        val bytes = buffer.getBytes(pos + 4, pos + 4 + length)
        return mapper.readValue(bytes, clazz)
    }
    ...
}

register codec for each class I want to serialize:

vertx.eventBus()
        .registerDefaultCodec(A::class.java, JacksonCodec(DatabindCodec.mapper(), A::class.java))
    vertx.eventBus()
vertx.eventBus()
        .registerDefaultCodec(B::class.java, JacksonCodec(DatabindCodec.mapper(), B::class.java))
    vertx.eventBus()

The code examples are kotlin but same applies for Java.


Solution

  • As far as I can tell looking at the code, there is no way, as the class needs to be the exact match:

    https://github.com/eclipse-vertx/vert.x/blob/master/src/main/java/io/vertx/core/eventbus/impl/CodecManager.java#L99