Skip to content
Advertisement

How can I specify the second parameter in ObjectMapper based on a variable in Java?

I have a use case where I am consuming from multiple topics and based on the topic I have to create an object from a String. I have around 25 topics leading to 25 kinds of objects. So, instead of using a bunch of if-else, I want to use a map where the key will be the topic name. So, instead of doing this,

JavaScript

I want to do this

JavaScript

Event is an interface implemented by all the classes, topic will store the topic name.

This is how I am creating ObjectMapper –

JavaScript

How can I achieve this? Thanks in advance

Advertisement

Answer

Your map will contain topicNames and what class they should be mapped to. All classes implement Event.class

JavaScript

JavaScript

The extends keyword may be used to qualify that to “any class which extends/implements Event

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement