专栏名称: 朱小厮的博客
著有畅销书:《深入理解Kafka》和《RabbitMQ实战指南》。公众号主要用来分享Java技术栈、Golang技术栈、消息中间件(如Kafka、RabbitMQ)、存储、大数据以及通用型技术架构等相关的技术。
目录
相关文章推荐
archrace  ·  上海和睿规划建筑设计有限公司 / ... ·  2 天前  
gooood谷德设计网  ·  SALT Architects|南非水源管理补给厂 ·  2 天前  
archrace  ·  Triptyque 新作 / ... ·  3 天前  
gooood谷德设计网  ·  上海/杭州招聘 | 否则建筑 ... ·  5 天前  
gooood谷德设计网  ·  MVRDV|曼谷设计周 – Mega Mat装置 ·  4 天前  
51好读  ›  专栏  ›  朱小厮的博客

面试官:说说Java中java.lang.Void和void有什么作用和区别?

朱小厮的博客  · 公众号  ·  · 2019-11-09 08:41

正文

点击上方“ 朱小厮的博客 ”,选择“ 设为星标

后台回复"加群",加入皮皮专属交流群


来源:http://suo.im/5p28k2


void关键字表示函数没有返回结果,是java中的一个关键字。

java.lang.Void是一种类型。例如给Void引用赋值null。

Void nil = null;

通过Void类的代码可以看到,Void类型不可以继承与实例化。

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

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 用来保存结果。Future的get方法会返回结果(类型为T)。

但如果操作并没有返回值呢?这种情况下就可以用Future 表示。当调用get后结果计算完毕则返回后将会返回null。

另外Void也用于无值的Map中,例如Map 这样map将具Set 有一样的功能。

因此当你使用泛型时函数并不需要返回结果或某个对象不需要值时候这是可以使用java.lang.Void类型表示。

java.lava.Void与void的比较 ,
http://stackoverflow.com/questions/10839042/what-is-the-difference-between-java-lang-void-and-void

如何判断函数返回void,
http://stackoverflow.com/questions/1924253/how-to-determine-by-reflection-if-a-method-returns-void







请到「今天看啥」查看全文