The “Void” as wrapper for “void” | Techbirds

I always try to bring some thing new and useful on this blog. This time we will understand the Void.class (which in itself looks something tricky) present in rt.jar.

One can consider the java.lang.Void class as a wrapper for the keyword void.

Some developers draw the analogy with the primitive data types int, long, short and byte etc. which have the wrapper classes as Integer, Long, Short and Byte receptively. But it should be kept in mind that unlike those wrappers Void class doesn’t store a value of type void in itself and hence is not a wrapper in true essence.

Purpose:

The Void class according to javadoc exists because of the fact that some time we may need to represent the void keyword as an object. But at the same point we cannot create an instance of the Void class using the new operator.

This is because the constructor in Void has been declared as private. 
Moreover the Void class is a final class which means that there is no way we can inherit this class.

So the only purpose that remains for the existence of the Void class is reflection, where we can get the return type of a method as void. The following piece of code will demonstrate this purpose:

public class Test { public static void main(String[] args) throws SecurityException, NoSuchMethodException { Class c1 = Test1.class.getMethod(“Test1”,null).getReturnType(); System.out.println(c1 == Void.TYPE); System.out.println(c1 == Void.class); } } class Test1{ public void Test1(){} }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class Test {

  public static void main(String[] args) throws SecurityException, NoSuchMethodException {

    Class c1 = Test1.class.getMethod(“Test1”,null).getReturnType();

    System.out.println(c1 == Void.TYPE);

    System.out.println(c1 == Void.class);

  }

}

class Test1{

public void Test1(){}

}

One can also use Void class in Generics to specify that you don’t care about the specific type of object being used. For example:

List list;

You’d use it mostly in a callback situation where you’re not actually returning anything but still need to specify a type because it might be used in a case where a type is returned. i.e.:

new Callback() { public void onSuccess(Void myResult) { //myResult == null } }

new Callback() {

    public void onSuccess(Void myResult) {

         //myResult == null

    }

}

You can’t use new to make a Void, but you can make one through setting it to null:

Void myValue = null;

979 total views, 2 views today

Share this Onfacebook-5006100twitter-5414311linkedin-1139546google-4709661