首页 > 解决方案 > 谓词接口中的 Java 泛型方法

问题描述

这是 Predicate 功能接口的代码:

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

为什么默认方法在方法签名中的返回类型之前and不使用类型参数?<T>

我认为default <T> Predicate<T> and(Predicate<? super T> other)是正确的,因为这是使用返回类型Predicate<T>

标签: javagenerics

解决方案


Obicere 已经提到过。

and返回并接受与 具有相同泛型类型的 Predicate this

Predicate<String> isNotNull = s -> s != null;
Predicate<String> andNotEmpty = isNotNull.and(s -> s.length() > 0);

虽然isEqualstatic不会“继承”其类声明的泛型类型并定义自己的<T>. 与修复对象相比,它更像是创建 Predicate 的工厂方法。

Predicate<String> isEqualToSth = Predicate.isEqual("sth");

推荐阅读