java - 自定义谓词链接

标签 java java-8

我正在学习 Java 8。我正在尝试创建自定义谓词链接方法,如下所示

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        return t -> this.test(t) && other.test(t);
    }
}

当我按上面的方式定义我的谓词时,它可以工作,但是如果我尝试实现与下面相同的东西,它会给我 StackOverflow 异常

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return test(t) && other.test(t);
            }
        };
    }
}

你能解释一下为什么它会给我 Java 7 风格的 stackoverflow 异常,而如果我使用 lambda 定义它则不给出任何异常。

最佳答案

test(t) 是对自身的递归调用,因为不合格的调用是对匿名类的。

this.test(t) 也是如此,因为 this 指的是匿名类。

更改为 Predicate.this.test(t)

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return Predicate.this.test(t) && other.test(t);
            }
        };
    }
}

参见 answer to "Lambda this reference in java"了解更多详情。

关于java - 自定义谓词链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52565057/

相关文章:

java - 使用 ComparisonChain over Objects.equal() && Objects.equal() ... with Guava 有什么好处

Java 8 Stream Collectors - 用于创建包含多个存储桶中的对象的 Map 的收集器

java - 使用Stream机制的filter()和map()方法的示例

generics - java 8谓词类型不匹配,这段代码对我来说似乎合乎逻辑

java - 从文本到二维数组的网格

java - 有没有办法阻止用户访问 Resteasy 中的 PUT、POST 和 DELETE 资源?

java - 如何将监听器添加到分隔符位置?

java - tkinter python 程序可以镜像到 android 应用程序上吗

java - 如何从 Instant.now() 获取 DayOfWeek

java - CommonPool 而非自定义池中的 ParallelStream 队列任务