如果方法的返回类型是Void,我该返回什么? (不是空的!) [英] What do I return if the return type of a method is Void? (Not void!)

查看:211
本文介绍了如果方法的返回类型是Void,我该返回什么? (不是空的!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在Java中使用泛型,我最终不得不实现一个具有 Void 作为返回类型的函数:

  public Void doSomething(){
// ...
}

,编译器要求我返回 。现在我只是返回 null ,但我想知道这是否是好的编码练习...



我也试过 Void.class void Void.TYPE new Void(),根本没有任何回报,但根本不起作用。 (或多或少显而易见的原因)(见这个答案


  • 那么我应该返回什么如果函数的返回类型是 Void

  • Void 类的常规用途是什么?



编辑:只是为了让你省钱:我问的是 V oid,而不是 v oid。 class Void not 保留关键字 void

$ b $如果函数的返回类型必须是 Void 那么我应该返回什么呢? / code>?

使用返回null Void 不能被实例化,仅仅是 Class 类型


Void


如上所述,它是一个占位符。例如,如果您使用反射来查看返回类型为 void Void $ C>。 (从技术上讲,你会得到 Class< Void> 。)它还有其他各种用途,就像你想参数化一个 Callable< ; T>


由于在Java中使用泛型,我最终不得不实现这个函数

如果您需要使用此签名来实现方法,那么您可能会说您的API有些时髦。仔细考虑是否有更好的方法去做你想做的事(也许你可以在不同的后续问题中提供更多的细节)。我有点怀疑,因为这只是由于使用泛型。

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() {
    //...
}

and the compiler demands that I return something. For now I'm just returning null, but I'm wondering if that is good coding practice...

I've also tried Void.class, void, Void.TYPE, new Void(), no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See this answer for details)

  • So what am I supposed to return if the return type of a function is Void?
  • What's the general use of the Void class?

EDIT: Just to spare you the downvotes: I'm asking about V‌oid, not v‌oid. The class Void, not the reserved keyword void.

解决方案

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

这篇关于如果方法的返回类型是Void,我该返回什么? (不是空的!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆