//interface
public interface NotificationPayload {
}
//Classes implement interface
public ClassA implements NotificationPayload {...}
public ClassB implements NotificationPayload {...}
...
public ClassX implements NotificationPayload {...}
//Message to send
public class Notification<T extends NotificationPayload> {
private T data; //T may be ClassA/ClassB/ClassC.../ClassX
...
}
When I receive a message as a json, I want to convert it to Notification again by using ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)
json example:
{
"type":"ClassA",
"userId":10087
}
I convert it:
Notification notif = objectMapper.readValue(json, Notification.class);
it throw exception:
java.lang.IllegalArgumentException: Can not construct instance of
com.common.kafka.notification.NotificationPayload: abstract types
either need to be mapped to concrete types, have custom deserializer, or
contain additional type information
at [Source: N/A; line: -1, column: -1] (through reference chain:
com.common.kafka.notification.Notification["data"])
I had read from this question: Cannot construct instance of - Jackson but seem like It cannot help because I have too many Class implement from interface, not only once.