Java 如何通过反射确定方法是否返回“void”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1924253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:29:20  来源:igfitidea点击:

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

javareflectionmethods

提问by Pablo Fernandez

I have a java.lang.reflect.Methodobject and I would like to know if it's return type is void.

我有一个java.lang.reflect.Method对象,我想知道它的返回类型是否为void.

I've checked the Javadocsand 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.

我检查了Javadocs,有一个getReturnType()方法可以返回一个 Class 对象。问题是,如果方法为空,他们没有说明返回类型是什么。

Thanks!

谢谢!

采纳答案by OscarRyz

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 

回答by James Keesey

It returns java.lang.Void.TYPE.

它返回java.lang.Void.TYPE

回答by Tom Hawtin - tackline

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

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

回答by Nom1fan

There is another, perhaps less conventional way:

还有另一种可能不太传统的方法:

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

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

回答by footman

method.getReturnType()==void.class     √

method.getReturnType()==Void.Type      √

method.getReturnType()==Void.class     X