首页 > 解决方案 > REST API:扩展泛型类的原始类型警告

问题描述

我有一堆看起来像这样的 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 设计还是你们有其他想法来解决这个问题。另一个想法是代替扩展 Base.class 我可以使用静态方法做某种实用类。但我需要先检查一下

标签: javagenericsraw-types

解决方案


您只需从基类中删除 <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) {
        // ...
    }
}

推荐阅读