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 Class TYPE = (Class) Class.getPrimitiveClass("void");

/*

* The Void class cannot be instantiated.

*/

private Void() {}

}

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

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

在看其中的这段代码:

@SuppressWarnings("unchecked")

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

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

/**

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

* {@code int}.

*

* @since JDK1.1

*/

@SuppressWarnings("unchecked")

public static final Class TYPE = (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类来作为返回值。

Future f = pool.submit(new Callable() {

@Override

public Void call() throws Exception {

......

return null;

}

});

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

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

相关推荐

[高清组图]世界杯:德国队问鼎 更衣室忘情欢庆
英国最大赌博365网站

[高清组图]世界杯:德国队问鼎 更衣室忘情欢庆

📅 07-07 👁️ 515
三五成群是什么生肖(三五成群是什么生肖正确答案)
晋江怎么充值比较划算
beat365网合法吗

晋江怎么充值比较划算

📅 07-10 👁️ 9971