What is the need of Void class in Java

JavaVoid

Java Problem Overview


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

Java Solutions


Solution 1 - Java

It also contains Void.TYPE, useful for testing return type with reflection:

public void foo() {}
...
if (getClass().getMethod("foo").getReturnType() == Void.TYPE) ...

Solution 2 - Java

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);
    }
}

Solution 3 - Java

Actually there is a pragmatic case where void.class is really useful. Suppose you need to create an annotation for class fields, and you need to define the class of the field to get some information about it (in example, if the field is an enum, to get list of potential values). In that case, you would need something like this:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyResourceMapper
{
    public Class acceptedValues() default void.class;
}

to be used like this:

@PropertyResourceMapper(acceptedValues = ImageFormat.class, description = "The format of     the image (en example, jpg).")
private ImageFormat format;

I have used this to create a custom serializer of classes to a proprietary format.

Solution 4 - Java

From the Java docs:

public final class Void
extends Object

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

static Class<Void> TYPE 

The Class object representing the primitive Java type void.

TYPE
public static final Class<Void> TYPE

The Class object representing the primitive Java type void.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongiriView Question on Stackoverflow
Solution 1 - JavaaxtavtView Answer on Stackoverflow
Solution 2 - JavaTofuBeerView Answer on Stackoverflow
Solution 3 - JavajuancancelaView Answer on Stackoverflow
Solution 4 - JavaArulrajView Answer on Stackoverflow