自定义谓词链接

Ish*_*rav 3 java java-8

我正在学习Java 8.我正在尝试创建自定义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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我如上所述定义我的谓词时它可以工作,但是如果我尝试实现与下面相同的它,它会给我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);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*eas 6

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);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅"在Java中使用Lambda此引用"的答案.