亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號