Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 927
Pablo Fernandez Avatar asked Dec 17 '09 20:12

Pablo Fernandez


People also ask

What is returned by a method of type void?

Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

Does a void method return null?

As shown above, in order to return from a method with the Void return type, we just have to return null. Moreover, we could have either used a random type (such as Callable<Integer>) and return null or no type at all (Callable), but using Void states our intentions clearly.

What characterizes a void method in Java?

Void methods do some action (called a side-effect); they do not return any value; Type methods return some value; they do not do an action. Examples of void methods include output methods such as: outputInt, outputDouble, outputString, outputlnInt, etc.

How do you call a void method in Java?

The void Keyword This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example.


2 Answers

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  
like image 97
OscarRyz Avatar answered Sep 18 '22 08:09

OscarRyz


method.getReturnType()==void.class     √  method.getReturnType()==Void.Type      √  method.getReturnType()==Void.class     X 
like image 25
footman Avatar answered Sep 21 '22 08:09

footman