问题描述
由于在Java中使用泛型,我最终不得不实现一个具有 Void
作为返回类型的函数:
public Void doSomething(){
// ...
}
,编译器要求我返回 。现在我只是返回 null
,但我想知道这是否是好的编码练习...
我也试过 Void.class
, void
, Void.TYPE
, new Void()
,根本没有任何回报,但根本不起作用。 (或多或少显而易见的原因)(见)
- 那么我应该返回什么如果函数的返回类型是
Void
? -
Void
类的常规用途是什么?
编辑:只是为了让你省钱:我问的是 V oid,而不是 v oid。 class Void
, not 保留关键字 void
。
Void 那么我应该返回什么呢? / code>?
使用返回null
。 Void
不能被实例化,仅仅是 Class
类型
。如上所述,它是一个占位符。例如,如果您使用反射来查看返回类型为 void $ c的方法,那么
Void
$ C>。 (从技术上讲,你会得到 Class< Void>
。)它还有其他各种用途,就像你想参数化一个 Callable< ; T>
。
如果您需要使用此签名来实现方法,那么您可能会说您的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 Void, not void. The class Void
, not the reserved keyword void
.
Use return null
. Void
can't be instantiated and is merely a placeholder for the Class<T>
type 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>
.
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,我该返回什么? (不是空的!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!