0
点赞
收藏
分享

微信扫一扫

编码技巧——Java Void 和 void 的区别

沉浸在自己的世界里 2022-04-25 阅读 68
java

在开发过程中,使用JDK的一些自带API时,遇到一个问题:需要传入一个方法A和一个降级方法B,降级方法B的方法签名是有返回参数的,而且返回参数类型需要跟方法A保持一致,编译器会作检查;

例如:使用CompletableFuture的exceptionally(),异步方法返参为void类型,这里的传参怎么传?

 

当方法A被定义成void类型的无返回参数的方法,方法B应该如何定义呢?——编译器提示我们定义一个返回值为Void类型的方法;本篇介绍下Void和void的区别;

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

void 关键字表示函数没有返回结果,是 java 中的一个关键字java.lang.Void是一种类型,例如给 Void 引用赋值 null 的代码为 Void nil = null;。

通过 Void 类的源代码可以看到,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 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 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> 有一样的功能;

因此当你使用泛型时函数并不需要返回结果,或者在使用JDK或第三方的API的时候,要求方法签名必须是有返回值的,而实际上需要传递一个void函数,这时可以使用 java.lang.Void 类型表示,并在方法结尾返回一个null即可。
 

参考:

What is the difference between java.lang.Void and void? - Stack Overflow

java - How to determine by reflection if a Method returns 'void' - Stack Overflow

举报

相关推荐

0 条评论