为了账号安全,请及时绑定邮箱和手机立即绑定

REST API:扩展通用类的原始类型警告

REST API:扩展通用类的原始类型警告

繁星点点滴滴 2023-06-28 16:11:16
我有一堆 RestController 类,看起来像这样:public class CategoryController {    private final IModelService modelservice;    private final ICacheHelper cacheHelper;    public CategoryController (IModelService modelservice, ICacheHelper cachehelper) {    this.modelservice = modelservice;    this.cachehelper = cachehelper;    @GetMapping("/foo/bar")    public ResponseEntity<Model1> getModel1 () {        Model1 model1 = modelService.getModel1();        if (model1 == null) {            return ResponseEntity.notFound().build();        }    return ResponseEntity.ok().build();    }    @GetMapping("/foo/bar/baz")    public ResponseEntity<Model2> getModel2 () {        Model2 model2 = modelservice.getModel2();        if (model2 =? null) {            return ResponseEntity.notFound().build();        }    return ResponseEntity.ok().build();    }}所以我创建了一个 Base.class 其中包含以下内容public class Base<T> {    private final ICacheHelper cachehelper;    public Base(ICacheHelper cachehelper) {        this.cachehelper = cachehelper;    public ResponseEntity<T> simpleResponse(T object, CacheControl cacheControl) {        return object != null            ? ResponseEntity.ok().cacheControl(cacheControl).body(object)            : ResponseEntity.notFound().cacheControl(cacheHelper.getErrorMaxAge()).build();然后,我使用 Base 扩展了 CategoryController,但没有泛型。所以我可以使用我的 simpleResponse。我理所当然地收到了很多关于 IntelliJ 中未经检查的作业的警告。我对泛型了解得越多,我就越明白这根本不是一个好主意,只有由于遗留原因才可能实现。有谁知道如何更好地做到这一点并以正确的方式使用泛型?我想到了重构RestController,并使它们基于returnValue。这意味着我需要为每个想要返回额外 ControllerClass 的模型创建。那么我可以public class Model1Controller extends Base<Model1> {    // do stuff}这是一个好的 API 设计吗?或者你们有其他想法来解决这个问题吗?另一个想法是我可以使用静态方法做某种 util 类,而不是扩展 Base.class。但我需要先检查一下
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

您只需从基类中删除 <T> 并将 <T> 移动到泛型方法中即可。它将删除未经检查的铸件的警告:


public class Base {


    private final ICacheHelper cachehelper;


    public Base(ICacheHelper cachehelper) {

        this.cachehelper = cachehelper;

    }


    public <T> ResponseEntity<T> simpleResponse(T object, CacheControl cacheControl) {

         // ...

    }


    public <A> ResponseEntity<A> anotherSimpleResponse(A object, CacheControl cacheControl) {

        // ...

    }

}


查看完整回答
反对 回复 2023-06-28
  • 1 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信