I am not clear with the class java.lang.Void
in Java. Can anybody elaborate in this with an example.
views:
474answers:
3
+11
A:
Say you want to have a generic that returns void for something:
abstract class Foo<T>
{
abstract T bar();
}
class Bar
extends Foo<Void>
{
Void bar()
{
return (null);
}
}
TofuBeer
2010-02-28 20:04:56
The problem is that Void class exists since jdk 1.1.
Roman
2010-02-28 22:47:56
I like TofuBeer's answer, but Roman raised an interesting point there.
Willi
2010-02-28 23:30:54
It isn't there strictly for that, it was just the first use that jumped to mind. The reflection answer is why it was introduced.
TofuBeer
2010-03-01 00:39:05
+12
A:
It also contains Void.TYPE
, useful for testing return type with reflection:
public void foo() {}
...
if (getClass().getMethod("foo").getReturnType() == Void.TYPE) ...
axtavt
2010-02-28 20:07:48
+1 for pointing that it is used in reflection to specify the type of a method, which has no return value.
stacker
2010-02-28 21:09:17
Actually there is also void.class (lowercase!) which would also works perfectly in your example. So Void is not needed there.
Willi
2010-02-28 23:27:45
In fact, Void.TYPE is defined as public static final Class<Void> TYPE = Class.getPrimitiveClass("void");Which itself is void.class.
Willi
2010-02-28 23:29:42
A:
public final class Voidextends ObjectThe Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
static Class TYPE The Class object representing the primitive Java type void.
TYPE public static final Class TYPEThe Class object representing the primitive Java type void.
Arulraj
2010-08-14 20:44:13