jeudi 16 avril 2020

How to Avoid casting when dealing inheritance with jackson

use-case : For a config class, I need to use a translator class.

I have 3 config classes (A,B,C) and 3 translator classes (X,Y,Z).

A is parent config class and (B,C) are subclasses. Similarly X is parent translator class and (Y,Z) are subclasses.

Translator Y translates B and Translator Z translates C ie ( B -> Y, C -> Z)

NOW, I receive a string input (for config class) and I use jackson to deserialise it to a type of config class A. With Jackson, I have mentioned subTypes and Jackson is able to deserialise it to required subtypes B or C correctly.

A a = new ObjectMapper().readValue(inputString, A.class)

Now, I want to do something like :

if(a.type == 'B') Y.process((B)a) // Since translator Y was for B subClass
if(a.type == 'C') Z.process((C)c)//  Since translator Z was for C subClass

is there a way, I can avoid typecasting here.

Aucun commentaire:

Enregistrer un commentaire