java.lang.Void 解析与使用

今天在查看源码的时候发现了 java.lang.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() {}
}

从源码中发现该类是final的,不可继承,并且构造是私有的,也不能 new。

那么该类有什么作用呢?

下面是我们先查看下 java.lang.Integer 类的源码

我们都知道 int 的包装类是 java.lang.Integer

从这可以看出 java.lang.Integer 是 int 的包装类。

同理,通过如下 java.lang.Void 的源码可以看出 java.lang.Void 是 void 关键字的包装类。

public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");

Void 使用

Void类是一个不可实例化的占位符类,如果方法返回值是Void类型,那么该方法只能返回null类型。
示例如下:

public Void test() { 
    return null;
}
使用场景一:
Future<Void> f = pool.submit(new Callable() {
    @Override
    public Void call() throws Exception {
        ......
        return null;
    }

});

比如使用 Callable接口,该接口必须返回一个值,但实际执行后没有需要返回的数据。 这时可以使用Void类型作为返回类型。

使用场景二:

通过反射获取所有返回值为void的方法。

public class Test {
    public void hello() { }
    public static void main(String args[]) {
        for (Method method : Test.class.getMethods()) {
            if (method.getReturnType().equals(Void.TYPE)) {
                System.out.println(method.getName());
            }
        }
    }
}

执行结果:

main
hello
wait
wait
wait
notify
notifyAll

想了解更多精彩内容请关注我的公众号

本人简书blog地址:http://www.jianshu.com/u/1f0067e24ff8    
点击这里快速进入简书

GIT地址:http://git.oschina.net/brucekankan/
点击这里快速进入GIT

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值