Java中 java.lang.Void和void 有什么作用和区别?

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

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 类型表示。