'Generic Method not implicitly constructing Parameter Class as Subclass when deserializing PostRequestBody
@PostMapping("")
<T extends FormEntity> ServiceResponse newService(@RequestHeader("form-class")Class<T> clazz, @RequestBody @NotNull T genericFormEntity) {
Service service = genericFormEntity.instantiateService();
serviceHashMap.put(service.getId(), service);
UUID id = service.getId();
return getServiceResponse(id);
}
Hi,
Java/ Spring Boot are reading genericFormEntity as FormEntity (an abstract class) at which point my code errors (because abstract classes can't be constructed). How can I make Java/ Spring Boot construct genericFormEntity as a JVMFormEntity (Class that extends FormEntity and is supposed to be provided by Class clazz)?
Above my latest attempt :)
Solution 1:[1]
If the content type of the request bodies is application/json, the following can be a simple solution.
@Autowired
private ObjectMapper objectMapper;
@PostMapping("...")
public ServiceResponse newService(@RequestHeader("form-class") String fullyQualifiedClassName, HttpServletRequest req)
throws ClassNotFoundException, IOException {
try (InputStream is = req.getInputStream()){
FormEntity formEntity =
(FormEntity) objectMapper.readValue(is, Class.forName(fullyQualifiedClassName));
// do something...
}
}
The value of form-class should be a 'FQCN'(fully qualified class name). For example, if your JVMFormEntity is in com.example package, the value should be com.example.JVMFormEntity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
