title: Spring MVC: How to return different type in ResponseEntity body
body: <p>In my request handler I want to do some validation and based on the outcome of validation check I will return different response (success/error). So I create a abstract class for the response object and make 2 subclasses for failure case and successful case. The code looks something like this, but it doesn't compile, complaining that errorResponse and successResponse cannot be converted to AbstractResponse.</p>
  
  <p>I'm quite new to Java Generic and Spring MVC so I don't know of a simple way to solve this.</p>
  
  <pre><code>@ResponseBody ResponseEntity&lt;AbstractResponse&gt; createUser(@RequestBody String requestBody) {
      if(!valid(requestBody) {
          ErrorResponse errResponse = new ErrorResponse();
          //populate with error information
          return new ResponseEntity&lt;&gt; (errResponse, HTTPStatus.BAD_REQUEST);
      }
      createUser();
      CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
      // populate with more info
      return new ResponseEntity&lt;&gt; (successResponse, HTTPSatus.OK);
  }
  </code></pre>