反序列化 PostRequestBody 时,泛型方法不会隐式构造参数 Class 作为子类
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);
}
嗨,
Java/ Spring Boot 正在将 genericFormEntity 读取为 FormEntity(抽象 class),此时我的代码错误(因为抽象 classes 不能建)。我怎样才能使 Java/ Spring 引导构造 genericFormEntity 作为 JVMFormEntity(Class 扩展 FormEntity 并且应该由 Class clazz 提供)?
以上是我最近的尝试:)
如果请求体的内容类型是application/json
,下面是一个简单的解决方案。
@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...
}
}
form-class
的值应该是 'FQCN'(完全限定的 class 名称)。例如,如果您的 JVMFormEntity
在 com.example
包中,则该值应为 com.example.JVMFormEntity
.
@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);
}
嗨,
Java/ Spring Boot 正在将 genericFormEntity 读取为 FormEntity(抽象 class),此时我的代码错误(因为抽象 classes 不能建)。我怎样才能使 Java/ Spring 引导构造 genericFormEntity 作为 JVMFormEntity(Class 扩展 FormEntity 并且应该由 Class clazz 提供)?
以上是我最近的尝试:)
如果请求体的内容类型是application/json
,下面是一个简单的解决方案。
@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...
}
}
form-class
的值应该是 'FQCN'(完全限定的 class 名称)。例如,如果您的 JVMFormEntity
在 com.example
包中,则该值应为 com.example.JVMFormEntity
.