简体   繁体   中英

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!

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

void.class method.getReturnType()返回void.class / Void.TYPE

它返回java.lang.Void.TYPE

还有另一种可能不那么传统的方式:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM