What do I return if the return type of a method is Void? (Not void!)

前端 未结 6 1096
忘掉有多难
忘掉有多难 2020-12-07 12:12

Due to the use of Generics in Java I ended up in having to implement a function having Void as return type:

public Void doSomething() {
    //..         


        
相关标签:
6条回答
  • 2020-12-07 12:23

    There's no way to instantiate a Void, so the only thing you can return is null.

    0 讨论(0)
  • 2020-12-07 12:25

    If, for obscure reasons, you MUST use this type, then indeed returning null seems to be a sensible option, since I suppose return value will not be used anyway.
    The compiler will force you to return something anyway.
    And this class doesn't seem to have a public constructor so new Void() is not possible.

    0 讨论(0)
  • 2020-12-07 12:34

    To make clear why the other suggestions you gave don't work:

    Void.class and Void.TYPE point to the same object and are of type Class<Void>, not of Void.

    That is why you can't return those values. new Void() would be of type Void but that constructor doesn't exist. In fact, Void has no public constructors and so cannot be instantiated: You can never have any object of type Void except for the polymorphic null.

    Hope this helps! :-)

    0 讨论(0)
  • 2020-12-07 12:40

    So what am I supposed to return if the return type of a function has to be Void?

    Use return null. Void can't be instantiated and is merely a placeholder for the Class<T> type of void.

    What's the point of Void?

    As noted above, it's a placeholder. Void is what you'll get back if you, for example, use reflection to look at a method with a return type of void. (Technically, you'll get back Class<Void>.) It has other assorted uses along these lines, like if you want to parameterize a Callable<T>.

    Due to the use of generics in Java I ended up in having to implement this function

    I'd say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there's a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I'm a little suspicious, since this only came up "due to the use of generics".

    0 讨论(0)
  • 2020-12-07 12:40

    just like this.

    public Class TestClass {
        public void testMethod () {
            return;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 12:44

    return null is the way to go.

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