[英]Custom Predicate chaining
I am learning Java 8 . 我正在学习Java 8。 I am trying to create custom Predicate chaining method as below 我正在尝试创建自定义Predicate链接方法,如下所示
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<T> other){
return t -> this.test(t) && other.test(t);
}
}
When i define my Predicate as above it works , but if i try to implement the same as below it gives me StackOverflow exception 当我如上所述定义我的谓词时它可以工作,但是如果我尝试实现与下面相同的它,它会给我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);
}
};
}
}
Can you please explain me why it is giving me stackoverflow exception in Java 7 style whereas do not give any exception if i define it using lambda. 你可以解释一下为什么它给我Java 7风格的stackoverflow异常,而如果我用lambda定义它,不要给出任何异常。
test(t)
is a recursive call to itself, since the unqualified call is to the anonymous class. test(t)
是对自身的递归调用,因为非限定调用是匿名类。
So would this.test(t)
be, since this
refers to the anonymous class. 那么this.test(t)
是,因为this
指的是匿名类。
Change to Predicate.this.test(t)
改为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);
}
};
}
}
See answer to "Lambda this reference in java" for more detail. 有关更多详细信息,请参阅“在Java中使用Lambda此引用”的答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.