You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为泛型ClassAModel传递.class类型至RestClient的toEntity方法?

解决RestClient泛型实体转换问题

Java泛型存在类型擦除机制,直接使用ClassAModel<ClassCResponseModel>.class这种写法是不合法的——编译时泛型参数信息会被擦除,无法直接获取带泛型参数的Class对象。要解决这个问题,需要用Spring提供的ParameterizedTypeReference来保留完整的泛型类型上下文。

修改后的API调用代码如下:

responseEntity = commonUtil
                .getRestClient()
                .get()
                .uri(UtilConstant.URI)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .toEntity(new ParameterizedTypeReference<ClassAModel<ClassCResponseModel>>() {});

原理说明

ParameterizedTypeReference通过创建匿名内部类的方式,在运行时保留了泛型的具体类型信息。Spring的RestClient可以借助这个类解析出嵌套的泛型结构,从而正确将JSON响应反序列化为ClassAModel<ClassCResponseModel>类型的对象。

额外提示:你的ClassAModel和ClassBModel作为数据传输模型,不需要添加@Component注解(该注解用于标记Spring管理的Bean),可以考虑移除,避免不必要的Bean注册。

内容的提问来源于stack exchange,提问作者kee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:20:59