java - 谓词接口中的 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>
。
解决方案
Obicere 已经提到过。
and
返回并接受与 具有相同泛型类型的 Predicate this
。
Predicate<String> isNotNull = s -> s != null;
Predicate<String> andNotEmpty = isNotNull.and(s -> s.length() > 0);
虽然isEqual
它static
不会“继承”其类声明的泛型类型并定义自己的<T>
. 与修复对象相比,它更像是创建 Predicate 的工厂方法。
Predicate<String> isEqualToSth = Predicate.isEqual("sth");
推荐阅读
- cucumber - 用于 POST 休息呼叫的 Gherkins 功能文件
- python - Django:无法在现场登录,但在本地服务器上它可以工作,而不是在现场
- oracle - 在 Oracle 中为外部表创建存储(和自动化)过程
- powershell - 获取文件夹的用户权限,包括通过 AD 和本地组的间接权限
- php - php artisan serve 在 Laravel 5.5 中更新代码时被缓存或不响应。重新启动后,它每次都会再次工作
- php - PHP 5.6 中的动态变量行为
- php - PHP递归函数输出选择
- java - Apache pdfbox 将 tiff 转换为 PDF - 多线程还是顺序方法?
- azure - Microsoft 身份验证库 (msal.js) 多租户注册流程
- arrays - 过滤网格中的问题