[英]java template formal parameters with Void
我有两个实体扩展ResponseEntity:
public class VoidResponseEntity<Void> extends ResponseEntity<Void> {
... }
public class InfoResponseEntity<Info> extends ResponseEntity<Info> {
... }
public class Info {
long id
}
在另一种方法中,我应该返回其中一个:
public <T extends ?????> ResponseEntity<T> foo(...) {
if (condition1) {
return new InfoResponseEntity<Info>(new Info());
}
return new VoidResponseEntity<Void>();
}
我应该写什么而不是“ ?????” 在方法签名中,通配符? 还是只是T?
如果您的方法确定响应实体类型,那么我怀疑您的方法首先不应该是通用的:
public ResponseEntity<?> foo() {
if (condition1) {
return new InfoResponseEntity<Info>(new Info());
}
return new VoidResponseEntity<Void>();
}
换句话说,您的foo
方法说:“我返回某种响应实体,但是在编译时无法告诉您它将是什么类型的参数。”
此外,听起来您的具体类不应泛型-它们应该是:
public class VoidResponseEntity extends ResponseEntity<Void> {
...
}
public class InfoResponseEntity extends ResponseEntity<Info> {
...
}
目前Void
和Info
在你的VoidResponseEntity
和InfoResponseEntity
类类型参数-而不是 Void
和Info
,我怀疑你想要他们班。
根据JavaDoc的说法,如果您使用方法“ foo”作为控制器,则应传递ResponseEntity而不是Type参数。
源ResponseEntity的示例。
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
因此,在您的情况下,方法应如下所示(如果我之前的假设对这个问题是正确的)
public ResponseEntity<?> foo(...) {
if (condition1) {
return new InfoResponseEntity<Info>(new Info());
}
return new VoidResponseEntity<Void>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.