java – Why is the Void class needed?


Why does Java need the java.lang.Void class?


void.class == Void.TYPE will return true – thus, in most cases (for example, if you need to check the return type of a method through reflection), you can (and, in my opinion, should) use void.class – it’s clearer and not inadvertently confused with Void.class . So you can use it, for example, in cases where you have a generic class and you want the method to return nothing (i.e. so that the user of the class does not expect anything special to get from there):

interface I<T> {
    T doStuff();

class A implements I<Void> {
    public Void doStuff() {
        // ...
        return null; // ничего другого вернуть нельзя (если не хитрить с рефлексией, конечно)

UPD. For example, if the project regularly uses Callable<t> to perform some asynchronous tasks and do not want to interfere with it with Thread in situations where the result of the task should not return anything, you can implement Callable<Void> .

Scroll to Top