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!
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.
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.
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.
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.
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
method.getReturnType()==void.class √ method.getReturnType()==Void.Type √ method.getReturnType()==Void.class X
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With