答:void關鍵字表示函數沒有返回結果,是java中的一個關鍵字。java.lang.Void是一種類型,例如給Void引用賦值null的代碼為Void nil=null; 。
通過Void類的源代碼可以看到,Void類型不可以繼承與實例化。
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() {}
/**
* 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;
}
//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());
}
}
}
}
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 類型表示。
但如果操作並沒有返回值呢?這種情況下就可以用 Future<Void> 表示。當調用 get 后結果計算完畢則返回后將會返回 null。
另外 Void 也用於無值的 Map 中,例如 Map<T,Void> 這樣 map 將具 Set<T> 有一樣的功能。
因此當你使用泛型時函數並不需要返回結果或某個對象不需要值時候這是可以使用 java.lang.Void 類型表示。