有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java 8中使用可选参数调用方法

我有以下方法

public static Boolean test(String str, Optional<Boolean> test) {


}

但如果我试着这样称呼它

test("hello")

我得到一个错误,该方法需要两个参数

可选参数不应该允许我在不提供可选参数的情况下调用测试方法吗


共 (3) 个答案

  1. # 1 楼答案

    var-args一样Optional不是可选参数
    Optional是一个容器对象,它可能包含也可能不包含非空值

    因此,您可以如下方式调用该方法:

    test("...", Optional.of(true));
    

    或者

    test("...", Optional.empty());
    

    请注意var-args

    public static Boolean test(String str, Boolean... test) {    
     //...
    }
    

    这将是有效的:

    test("hello")
    

    但是var args不是传递可选参数的正确方法,因为它传递的是0个或多个对象,而不是0或1个对象

    方法重载更好:

    public static Boolean test(String str, Boolean test) {
     // ...
    }
    
    public static Boolean test(String str) {
     // ...
    }
    

    在其他一些情况下,@Nullable约束(JSR-380)可能也很有趣

  2. # 2 楼答案

    简而言之,Optional是一个类,在Java中,必须像定义方法一样将精确数量的参数传递给方法

    唯一的例外是在方法声明中将...放在类对象名称之后

    public String test (String X, String... Y) { }
    

    这使得第二个参数为either zero or more

  3. # 3 楼答案

    试试这个

    public static Boolean test(String str, Boolean ... test) {}
    

    它会对你有用的