今天在查看源碼的時候發現了 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 finalclass 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()); } } }}
執行結果:
mainhellowaitwaitwaitnotifynotifyAll
ps:下面介紹java.lang.Void 與 void的比較及使用
void關鍵字表示函數沒有返回結果,是java中的一個關鍵字。
java.lang.Void是一種類型。例如給Void引用賦值null。
Void nil = null;
通過Void類的代碼可以看到,Void類型不可以繼承與實例化。
public finalclass 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() {}}
Void作為函數的返回結果表示函數返回null(除了null不能返回其它類型)。
Void function(int a, int b) { //do something return null; }
在泛型出現之前,Void一般用于反射之中。例如,下面的代碼打印返回類型為void的方法名。
public class Test { public void print(String v) {} public static void main(String args[]){ for(Method method : Test.class.getMethods()) { if(method.getReturnType().equals(Void.TYPE)) { System.out.println(method.getName()); } } }}
泛型出現后,某些場景下會用到Void類型。例如Future<T>
用來保存結果。Future的get方法會返回結果(類型為T)。
但如果操作并沒有返回值呢?這種情況下就可以用Future<Void>
表示。當調用get后結果計算完畢則返回后將會返回null。
另外Void也用于無值的Map中,例如Map<T,Void>
這樣map將具Set<T>
有一樣的功能。
因此當你使用泛型時函數并不需要返回結果或某個對象不需要值時候這是可以使用java.lang.Void類型表示。
總結
以上所述是小編給大家介紹的java.lang.Void的類 解析與使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
新聞熱點
疑難解答
圖片精選