java – 自定义谓词链接
发布时间:2020-12-15 08:27:30 所属栏目:Java 来源:网络整理
导读:我正在学习 Java 8.我正在尝试创建自定义Predicate链接方法,如下所示 @FunctionalInterfacepublic interface PredicateT { boolean test(T t); default PredicateT and(PredicateT other){ return t - this.test(t) other.test(t); }} 当我如上所述定义我的
我正在学习
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); } } 当我如上所述定义我的谓词时它可以工作,但是如果我尝试实现与下面相同的它,它会给我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)是,因为这指的是匿名类. 改为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”. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |