java - 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 我可以使用静态方法做某种实用类。但我需要先检查一下
解决方案
您只需从基类中删除 <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) {
// ...
}
}
推荐阅读
- excel - 如何在excel的一列行中匹配一列字符串?
- c++ - 如何在 OpenSSL 库的名称中添加后缀“d”?
- javascript - 所有事件都有一个监听器数组还是所有“发射器”都有一个监听器数组?
- html - Iron Python 在 Spotfire 客户端的初始加载中触发,但对于 Spotfire Web 播放器没有触发
- python - 反应角色 Discord.py
- c# - C# 如何将时间 [ms, s, m, h, d] 作为字符串转换为秒作为 int
- automake - automake 需要 makeinfo 而 texinfo 需要 aclocal
- r - R Shiny 反应性错误,我该如何解决?
- javascript - 如何从 React-Router-Dom 停止对 Link 元素的传播?
- sql-server - 使用 JDBC 的命名管道连接