简体   繁体   English

带Void的Java模板形式参数

[英]java template formal parameters with Void

I have two entities extending ResponseEntity: 我有两个实体扩展ResponseEntity:

public class VoidResponseEntity<Void> extends ResponseEntity<Void> {
    ... }

public class InfoResponseEntity<Info> extends ResponseEntity<Info> {
    ... }

public class Info {
    long id
}

In my another method I should return one of it: 在另一种方法中,我应该返回其中一个:

public <T extends ?????> ResponseEntity<T> foo(...) {
     if (condition1) {
            return new InfoResponseEntity<Info>(new Info());
        }
        return new VoidResponseEntity<Void>();
}

What should I write instead of "?????" 我应该写什么而不是“ ?????” in method signature, wildcard? 在方法签名中,通配符? Or just T? 还是只是T?

If your method is deciding the response entity type, I suspect your method shouldn't be generic in the first place: 如果您的方法确定响应实体类型,那么我怀疑您的方法首先不应该是通用的:

public ResponseEntity<?> foo() {
    if (condition1) {
        return new InfoResponseEntity<Info>(new Info());
    }
    return new VoidResponseEntity<Void>();
}

In other words, your foo method is saying "I return some kind of response entity, but I can't tell you at compile time what the type argument it will be." 换句话说,您的foo方法说:“我返回某种响应实体,但是在编译时无法告诉您它将是什么类型的参数。”

Additionally, it sounds like your concrete classes shouldn't be generic - they should be: 此外,听起来您的具体类不应泛型-它们应该是:

public class VoidResponseEntity extends ResponseEntity<Void> {
    ...
}

public class InfoResponseEntity extends ResponseEntity<Info> {
    ... 
}

Currently the Void and Info in your VoidResponseEntity and InfoResponseEntity classes are type parameters - not the Void and Info classes that I suspect you wanted them to be. 目前VoidInfo在你的VoidResponseEntityInfoResponseEntity类类型参数-而不是 VoidInfo ,我怀疑你想要他们班。

According to JavaDoc if you are using the method "foo" as controller you should be passing the ResponseEntity not the Type parameter. 根据JavaDoc的说法,如果您使用方法“ foo”作为控制器,则应传递ResponseEntity而不是Type参数。

Example for source ResponseEntity. 源ResponseEntity的示例。

@RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
 }

So in your case the method should look like this (If my earlier assumption is correct about the question) 因此,在您的情况下,方法应如下所示(如果我之前的假设对这个问题是正确的)

public ResponseEntity<?> foo(...) {
     if (condition1) {
            return new InfoResponseEntity<Info>(new Info());
        }
        return new VoidResponseEntity<Void>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM