您可以使用 Java 8 的功能接口。
由于您需要 2 个操作数和一个布尔结果,您可以简单地使用 BiPredicate,但由于您希望 2 个操作数属于同一类型,因此您需要重复该类型,因此您可以创建一个新的功能界面,例如命名为BinaryPredicate:
interface BinaryPredicate<T> extends BiPredicate<T, T> {
// nothing to add
}
那么你的方法可能是,例如像这样,如果您希望操作数是实现Comparable 的类型:
public static <T extends Comparable<T>> BinaryPredicate<T> objectOperator(int value){
if (value < 0)
return (a, b) -> a.compareTo(b) >= 0;
return (a, b) -> a.compareTo(b) <= 0;
}
如果您希望操作数为 int 值,则可以改为创建:
interface IntBinaryPredicate {
boolean test(int a, int b);
}
然后像这样做你的方法:
public static IntBinaryPredicate intOperator(int value){
if (value < 0)
return (a, b) -> a >= b;
return (a, b) -> a <= b;
}
您将如何使用它们:
BinaryPredicate<String> stringOp = objectOperator(1);
if (stringOp.test("Foo", "Bar"))
IntBinaryPredicate intOp = intOperator(1);
if (intOp.test(13, 42))