【发布时间】:2020-09-03 19:37:27
【问题描述】:
我想使用默认方法“negate()”返回一个“关系”,它总是返回方法 test() 的反面。我该怎么做?
public interface Relation<X,Y> {
boolean test(X x, Y y);
default Relation<X,Y> negate() {
// TODO
Relation<X, Y> relation = new Relation<X, Y>() {
public boolean test(X x, Y y) {
return !this.test(x, y);
}
};
return relation;
}
}
我试过这段代码,但是它给了我堆栈溢出错误
【问题讨论】:
-
在
return !this.test(x, y);中,this.test是您定义的默认方法,因此它是无限递归。 -
default Relation<X, Y> negate() { return (x, y) -> !this.test(x, y); }