Home > Software engineering >  Generic Method not implicitly constructing Parameter Class as Subclass when deserializing PostReques
Generic Method not implicitly constructing Parameter Class as Subclass when deserializing PostReques

Time:03-10

  @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 :)

CodePudding user response:

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.

  • Related