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

REST API: Raw Type warning extending a Generic Class

我有一堆 RestController classes,看起来像这样:

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 来制作它们。这意味着我需要为每个我想要 return 的模型创建一个额外的 ControllerClass。然后我可以

public class Model1Controller extends Base<Model1> {
    // do stuff
}

这是一个很好的 API 设计吗?或者你们有其他想法来解决这个问题。 另一个想法不是扩展 Base.class 我可以用静态方法做一些 util class 。但我需要先检查一下

您只需从 Base class 中删除 并将 移动到泛型方法中。它将删除未经检查的铸件的警告:

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) {
        // ...
    }
}