Java generics void/Void types

后端 未结 6 1313
天命终不由人
天命终不由人 2020-12-08 09:36

I am implementing a ResponseHandler for the apache HttpClient package, like so:

new ResponseHandler() {
    public int handleResponse         


        
相关标签:
6条回答
  • 2020-12-08 09:47

    When you need to return java.lang.Void, just return null.

    0 讨论(0)
  • 2020-12-08 09:48

    The Void type was created for this exact situation: to create a method with a generic return type where a subtype can be "void". Void was designed in such a way that no objects of that type can possibly be created. Thus a method of type Void will always return null (or complete abnormally), which is as close to nothing as you are going to get. You do have to put return null in the method, but this should only be a minor inconvenience.

    In short: Do use Void.

    0 讨论(0)
  • 2020-12-08 09:51

    This java.lang.Void implementation in Java kind of speaks for itself. Also, I wrote an article that ties this into generics. It took a bit of thought before I started understanding this: http://www.siteconsortium.com/h/D00006.php. Notice TYPE = Class.getPrimitiveClass("void");

    package java.lang;

    public final class Void {
    
        public static final Class<Void> TYPE = Class.getPrimitiveClass("void");
    
        private Void() {}
    }
    
    0 讨论(0)
  • 2020-12-08 10:00

    Alas it's not possible. You can set the code to return Void as you say, however you can never instanciate a Void so you can't actually write a function which conforms to this specification.

    Think of it as: The generic function says "this function returns something, of type X", and you can specify X but you can't change the sentence to "this function returns nothing". (I'm not sure if I agree with these semantics, but that's the way they are.)

    In this case, what I always do, is just make the function return type Object, and in fact always return null.

    0 讨论(0)
  • Generics only handles object classes. void and primitive types are not supported by Generics and you cannot use these as a parameterized type. You have to use Void instead.

    Can you say why you don't want to use Void?

    0 讨论(0)
  • 2020-12-08 10:12

    You can't have primitives in generics so that int is actually an Integer. The object Void is analogous with the keyword void for generics.

    0 讨论(0)
提交回复
热议问题