How to determine by reflection if a Method returns 'void'

JavaReflectionMethods

Java Problem Overview


I have a java.lang.reflect.Method object and I would like to know if it's return type is void.

I've checked the Javadocs and there is a getReturnType() method that returns a Class object. The thing is that they don't say what would be the return type if the method is void.

Thanks!

Java Solutions


Solution 1 - Java

if( method.getReturnType().equals(Void.TYPE)){
    out.println("It does");
 }

Quick sample:

$cat X.java  

import java.lang.reflect.Method;


public class X {
    public static void main( String [] args ) {
        for( Method m : X.class.getMethods() ) {
            if( m.getReturnType().equals(Void.TYPE)){
                System.out.println( m.getName()  + " returns void ");
            }
        }
    }

    public void hello(){}
}
$java X
hello returns void 
main returns void 
wait returns void 
wait returns void 
wait returns void 
notify returns void 
notifyAll returns void 

Solution 2 - Java

method.getReturnType()==void.class     √

method.getReturnType()==Void.Type      √

method.getReturnType()==Void.class     X

Solution 3 - Java

method.getReturnType() returns void.class/Void.TYPE.

Solution 4 - Java

It returns java.lang.Void.TYPE.

Solution 5 - Java

There is another, perhaps less conventional way:

public boolean doesReturnVoid(Method method) { if (void.class.equals(method.getReturnType())) return true; }

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
QuestionPablo FernandezView Question on Stackoverflow
Solution 1 - JavaOscarRyzView Answer on Stackoverflow
Solution 2 - JavafootmanView Answer on Stackoverflow
Solution 3 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 4 - JavaJames KeeseyView Answer on Stackoverflow
Solution 5 - JavaNom1fanView Answer on Stackoverflow