tags:

views:

474

answers:

3

I am not clear with the class java.lang.Void in Java. Can anybody elaborate in this with an example.

+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
The problem is that Void class exists since jdk 1.1.
Roman
I like TofuBeer's answer, but Roman raised an interesting point there.
Willi
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
+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
+1 for pointing that it is used in reflection to specify the type of a method, which has no return value.
stacker
Actually there is also void.class (lowercase!) which would also works perfectly in your example. So Void is not needed there.
Willi
In fact, Void.TYPE is defined as public static final Class<Void> TYPE = Class.getPrimitiveClass("void");Which itself is void.class.
Willi
@Willi: Yes, I forget about `void.class`. Sorry.
axtavt
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