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

前端 未结 5 1187
滥情空心
滥情空心 2021-02-03 16:36

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

相关标签:
5条回答
  • 2021-02-03 17:07

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

    0 讨论(0)
  • 2021-02-03 17:10
    method.getReturnType()==void.class     √
    
    method.getReturnType()==Void.Type      √
    
    method.getReturnType()==Void.class     X
    
    0 讨论(0)
  • 2021-02-03 17:18

    It returns java.lang.Void.TYPE.

    0 讨论(0)
  • 2021-02-03 17:23
    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 
    
    0 讨论(0)
  • 2021-02-03 17:25

    There is another, perhaps less conventional way:

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

    0 讨论(0)
提交回复
热议问题