我正在学习 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);
}
};
}
}
关于java - 自定义谓词链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52565057/