简体   繁体   中英

java template formal parameters with Void

I have two entities extending 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?

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."

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.

According to JavaDoc if you are using the method "foo" as controller you should be passing the ResponseEntity not the Type parameter.

Example for source 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>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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