java – Generic“is null”谓词

参见英文答案 > Lambda as a combination of methods from the Predicate interface doesn’t compile if it is written as one statement                                    4个
我写了这个通用谓词:

private static <T> Predicate<T> isNull(){
    return Objects::isNull;
}

但我不能将它与其他类似的谓词结合使用:

private static Predicate<String> isEmpty(){
    return string -> string.isEmpty();
}

因为此代码段不会编译(期望Predicate< String> in或operation):

isNull().or(isEmpty())

有什么想法解决它吗?谢谢!

解决方法:

由于isNull()是通用的,并且编译器在组合时无法推断泛型参数,因此需要显式指定类型参数.

为此,您必须符合班级名称,例如:测试:

Test.<String>isNull().or(isEmpty())

完整示例:

public class Test {
    public static void main(String[] args) {
        Predicate<String> isNullOrEmpty = Test.<String>isNull().or(isEmpty());
        System.out.println(isNullOrEmpty.test(null));   // true
        System.out.println(isNullOrEmpty.test(""));     // true
        System.out.println(isNullOrEmpty.test("Foo"));  // false
    }
    private static <T> Predicate<T> isNull(){
        return Objects::isNull;
    }
    private static Predicate<String> isEmpty(){
        return string -> string.isEmpty();
    }
}

您还可以通过将每个部分分配给变量来解决它:

Predicate<String> isNull = isNull(); // String is inferred from assignment operator
Predicate<String> isEmpty = isEmpty();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty);

或者只是第一部分:

Predicate<String> isNull = isNull();
Predicate<String> isNullOrEmpty = isNull.or(isEmpty());
上一篇:C#委托的介绍(delegate、Action、Func、predicate)(转)


下一篇:Java 8 Streams – 将固定数量的谓词过滤器应用于单个Stream