日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java.lang.Void 解析与使用

發(fā)布時(shí)間:2024/9/30 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java.lang.Void 解析与使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

今天在查看源碼的時(shí)候發(fā)現(xiàn)了 java.lang.Void 的類。這個(gè)有什么作用呢?

先通過源碼查看下

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() {} }

從源碼中發(fā)現(xiàn)該類是final的,不可繼承,并且構(gòu)造是私有的,也不能 new。

那么該類有什么作用呢?

下面是我們先查看下 java.lang.Integer 類的源碼

我們都知道 int 的包裝類是 java.lang.Integer

從這可以看出 java.lang.Integer 是 int 的包裝類。

同理,通過如下 java.lang.Void 的源碼可以看出 java.lang.Void 是 void 關(guān)鍵字的包裝類。

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

Void 使用

Void類是一個(gè)不可實(shí)例化的占位符類,如果方法返回值是Void類型,那么該方法只能返回null類型。
示例如下:

public Void test() { return null; }

使用場(chǎng)景一:

Future<Void> f = pool.submit(new Callable() {@Overridepublic Void call() throws Exception {......return null;}});

比如使用 Callable接口,該接口必須返回一個(gè)值,但實(shí)際執(zhí)行后沒有需要返回的數(shù)據(jù)。 這時(shí)可以使用Void類型作為返回類型。

使用場(chǎng)景二:

通過反射獲取所有返回值為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());}}} }

執(zhí)行結(jié)果:

main hello wait wait wait notify notifyAll

想了解更多精彩內(nèi)容請(qǐng)關(guān)注我的公眾號(hào)

本人簡(jiǎn)書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點(diǎn)擊這里快速進(jìn)入簡(jiǎn)書

GIT地址:http://git.oschina.net/brucekankan/
點(diǎn)擊這里快速進(jìn)入GIT

總結(jié)

以上是生活随笔為你收集整理的java.lang.Void 解析与使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。