81

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!

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232

5 Answers5

125
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 
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 1
    For some reason with java 6 I had to replace `Void.TYPE` with `Void.class` otherwise the check would always fail. Ideas why? – Giovanni Botta Mar 26 '14 at 18:51
  • 2
    @GiovanniBotta Void.TYPE is the same as void.class and represents the primitive type void. Void.class represents the reference type Void. So maybe your method returns Void instead of void. – Bax Sep 19 '16 at 20:53
35
method.getReturnType()==void.class     √

method.getReturnType()==Void.Type      √

method.getReturnType()==Void.class     X
Alexan
  • 8,165
  • 14
  • 74
  • 101
footman
  • 451
  • 5
  • 8
11

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

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
8

It returns java.lang.Void.TYPE.

James Keesey
  • 1,218
  • 9
  • 13
0

There is another, perhaps less conventional way:

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

Nom1fan
  • 846
  • 2
  • 11
  • 27