java.lang.Void 与 void的比较及使用_public class void

CSDN博客 · · 134 次点击 · · 开始浏览    

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

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

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

因此当你使用泛型时函数并不需要返回结果或某个对象不需要值时候这是可以使用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

本文来自:CSDN博客

感谢作者:CSDN博客

查看原文:java.lang.Void 与 void的比较及使用_public class void

134 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传