There is no issue in using generics in Java unless it is implemented well. I have seen many projects using response wrappers for API calls in spring boot.
Here is an example where generics are used in response entity.
@Builder
@NoArgsConstructor
@Data
@AllArgsConstructor
public class Response<T extends Object> {
private LocalDateTime timestamp;
private int status;
private Boolean isSuccess;
private String message;
private T data;
}
It is a wrapper class where every API response will contain the following fields
public class ResponseWrapper {
public static <T extends Object> ResponseEntity<T> generateResponse(HttpStatus status, boolean isSuccess, String message, T responseObj) {
Response<Object> response = Response.builder().timestamp(LocalDateTime.now()).status(status.value()).isSuccess(isSuccess).message(message).data(responseObj).build();
return new ResponseEntity<T>((T) response, status);
}
public static <T extends Object> ResponseEntity<T> ok(T responseObj) {
return generateResponse(HttpStatus.OK, true, "", responseObj);
}
public static ResponseEntity<String> message(String message) {
return generateResponse(HttpStatus.OK, true, message, "");
}
public static ResponseEntity<String> error(String message, HttpStatus status) {
return generateResponse(status, false, message, "");
}
}
This is the wrapper that needs to be called from the controller
@GetMapping(value = "/dummy/users", produces = { Api.V10 })
public ResponseEntity<List<User>> getAllDummyUsers() {
return ResponseWrapper.ok(userService.getAllUsers());
}
Hope I understood the question and was able to provide an answer.