0

What are some issues using Generic Types in API Responses? Does it cause any coding bugs, issues, or compatibility headaches? Ccurrently using Java 8, Spring Boot 3, with React 17. I prefer using stable class types.

Generic type as parameter in Java Method

private static <T> List<T> pushBack(List<T> list, Class<T> typeKey) throws Exception {
    list.add(typeKey.getConstructor().newInstance());
    return list;
}

I see a problem thread here, https://github.com/swagger-api/swagger-core/issues/498

mattsmith5
  • 540
  • 4
  • 29
  • 67

1 Answers1

1

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.

alea
  • 980
  • 1
  • 13
  • 18