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

發佈了132 篇原創文章 · 獲贊 79 · 訪問量 40萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章