1

I am working on a service has to forward the incoming requests to a destination service after performing some alterations on the object received in the request body and return the response received from the service. There are only two types of objects (A or B) expected in the response body for which I want to use a wildcard instead of Object class to keep the code cleaner.

Now I know that we can not use generics with two classes such that the generic class object must belong to either of the two classes.

public ResponseEntity<?> getDataFromService(C requestBody) {
  C updatedRequestBody = performAlterationsOnRequestBody (requestBody);

  ResponseEntity<?> responseObject = forwardToRespectiveService(updatedRequestBody);
  // responseObject body can contain object of either class A or class B.
  return response;
}

Is the approach to use a wildcard correct way to go about?

  • If `A` and `B` don't share a useful superclass or interface, then using `?` is reasonable. Is there any indication as to when this would return `A` or `B`? Specifically, anything that could be known at compile time? – Joachim Sauer May 17 '23 at 11:11
  • 1
    For most purposes, there is no difference between `>` or ` extends Object>`. But this method `getDataFromService` doesn’t have any options anyway if `forwardToRespectiveService` is already returning a `ResponseEntity>`. – Holger May 17 '23 at 12:35
  • A and B are two completely different classes that do not share any superclass or interface. `forwardToRespectiveService` method fires a REST request to another service and gives me the response from that service. So, I do not have a way of differentiating at compile time the cases in which I get A or B. @JoachimSauer – Ashutosh Sharma May 18 '23 at 04:31
  • I have put the response of `forwardToRespectiveService` as `ResponseEntity>` because I do not know whether the response body would contain an object of class A or class B. I am returning the same response entity as such, hence the return type of `getDataFromService` is `ResponseEntiity>`. Clarifying on my original question a little more, I wanted to know if there is a better way to go about things. @Holger – Ashutosh Sharma May 18 '23 at 04:35

0 Answers0