java.lang.Void 解析与使用
今天在查看源碼的時(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類型。
示例如下:
使用場(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 注解 Annotation
- 下一篇: 网络传输 相关概念