Skip to content
Advertisement

What is the best way to define a common Base Java Model for all Responses?

I have a need to format all REST responses as:

JavaScript

Where the response is an arbitrary data (object, array; with arbitrary fields) different for each REST API endpoint.

What is the best way to define different response for each response Model ?

I tried this (and it works, but I’m not sure is it the right thing to do):

BaseResponseModel.java

JavaScript

and the subclass:

CustomerResponseModel.java

JavaScript

I used inner static class with fields in every subclass but I’m not sure is it the correct way to do.

Advertisement

Answer

In this case I wouldn’t go for inheritance but rather go for composition and leverage generics. The advantage of this approach is that you don’t require nested classes, you enforce the base REST model throughout your application while keeping the response type generic.

BaseResponseModel.java:

JavaScript

CustomerResponseModel.java:

JavaScript

Example of the usage:

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