JAVA类中 void,JAVA中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 ClassTYPE = (Class) Class.getPrimitiveClass("void");

/*

* The Void class cannot be instantiated.

*/

private Void() {}

}

通过类上面的注释我们知道Void是一个不可实例化的占位类。它持有关键字为void的Class的应用。

同时可以发现该类是final的,不可继承,并且构造是私有的,也不能 new。

在看其中的这段代码:

@SuppressWarnings("unchecked")

public static final ClassTYPE = (Class) Class.getPrimitiveClass("void");

如果你看过Integer类的源码,你会非常熟悉:

/**

* The {@code Class} instance representing the primitive type

* {@code int}.

*

* @since JDK1.1

*/

@SuppressWarnings("unchecked")

public static final ClassTYPE = (Class) Class.getPrimitiveClass("int");

这可以看出 java.lang.Integer 是 int 的包装类。同理, java.lang.Void 的源码可以看出 java.lang.Void 是 void 关键字的包装类。

Void 使用

所以这个类怎么用呢?

首先,因为Void是一个不可实例化的类,如果方法返回值是Void类型,那么该方法只能返回null。

public Void test() {

return null;

}

在泛型出现之前,Void一般用于反射之中。比如使用反射的时候获取返回值是void的方法。

if (method.getReturnType().equals(Void.TYPE)) {

......

}

泛型出现后,某些场景下会用到Void类型。比如我们要实现一个线程同时支持线程中抛出异常,那么我们就要使用Callable接口而不是Runnable接口。但是Callable的call方法必须有返回值,如果我们没有返回值怎么办?这里就可以使用Void类来作为返回值。

Futuref = pool.submit(new Callable() {

@Override

public Void call() throws Exception {

......

return null;

}

});

另外Void也用于无值的Map中,例如Map这样map将具Set有一样的功能。

因此当你使用泛型时函数并不需要返回结果或某个对象不需要值时候这是可以使用java.lang.Void类型表示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值