How to determine by reflection if the method returns 'void'

I have a java.lang.reflect.Method object and I would like to know if it returns a void type.

I checked Javadocs and there is a getReturnType() method that returns a class object. The fact is that they do not say what the return type will be if the method is invalid.

Thank!

+58
java reflection methods
Dec 17 '09 at 20:09
source share
5 answers
 if( method.getReturnType().equals(Void.TYPE)){ out.println("It does"); } 

Quick example:

 $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 
+91
Dec 17 '09 at 20:12
source share

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

+9
Dec 17 '09 at 20:12
source share

It returns java.lang.Void.TYPE .

+7
Dec 17 '09 at 20:12
source share
 method.getReturnType()==void.class √ method.getReturnType()==Void.Type √ method.getReturnType()==Void.class X 
+3
Jun 05 '17 at 3:58 on
source share

There is another, perhaps less traditional way:

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

0
Aug 11 '16 at 11:13
source share



All Articles