void 和 Void的区别

void 和 Void的区别:
void是用于没有返回值的方法的定义,比如:public void test(){ ………………}

Void是一个Class,是对void的包装,方法的返回值可以是Void,比如:public Void test(){ return null;} //这里Void类型的返回值只能是null
Void不能被实例化。可用于返回null或者泛型返回null的,还可以反射中判断返回值是void 比如:
if(method.getReturnType().equals(Void.TYPE)) {
    System.out.println(method.getName());
}
if(method.getReturnType().equals(void.Class)) {
    System.out.println(method.getName());
}

附录:Void的源码:

package java.lang;

/**
 * The {@code Void} class is an uninstantiable placeholder class to hold a
 * reference to the {@code Class} object representing the Java keyword
 * void.
 *
 * @author  unascribed
 * @since   JDK1.1
 */
public final
class Void {

    /**
     * The {@code Class} object representing the pseudo-type corresponding to
     * the keyword {@code void}.
     */
    @SuppressWarnings("unchecked")
    public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");

    /*
     * The Void class cannot be instantiated.
     */
    private Void() {}
}
发布了77 篇原创文章 · 获赞 90 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/weisong530624687/article/details/89841781