【问题标题】:Custom Predicate chaining自定义谓词链接
【发布时间】:2018-09-29 04:15:47
【问题描述】:

我正在学习 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 定义它则不给出任何异常。

【问题讨论】:

  • lambda 中的 this 不指代 lambda。在匿名内部类中,this 指的是内部类的实例。

标签: java java-8


【解决方案1】:

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"

【讨论】:

  • 根据您的回答,这也不应该工作 default Predicate and(Predicate other){ return t -> this.test(t) && other.test(t); } 。但这工作正常。怎么会这样?
  • @IshantGaurav 因为 lambda 不是匿名类,我提供的链接中对此进行了说明。
猜你喜欢
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多