如何使用一个方法作为另一个的参数?

我想创建一个使用另一个方法作为参数的方法。但是我该怎么做呢?我应该如何修改才能正确? (例如)

class Illustration
{
    public boolean condition1 (int a, double b)
    {
        return (a <= b)
    }
    public boolean condition2 (int a, double b)
    {
        return (a > b)
    }
    public double operation (int a, double b, Method cond)
    {
        if (cond(a, b))
        {
            return (a + b)
        } else {
            return (a - b)
        }
    }
}
评论
小梨涡
小梨涡

与其尝试将一个方法错误地传递为另一个方法的参数,不如使用它,

class Illustration
{
    public boolean condition1 (int a, double b)
    {
        return (a <= b)
    }
    public boolean condition2 (int a, double b)
    {
        return (a > b)
    }
    public double operation (int a, double b)
    {
        if (condition1(a, b))
        {
            return (a + b)
        } else {
            return (a - b)
        }
    }
}
点赞
评论
xnemo
xnemo

You can use java.util.function.BiPredicate for this one:

public double operation (int a, double b, BiPredicate<Integer, Double> cond) {
    if (cond.test(a, b)) { // returns true if a is less than b

并传递lambda:

operation(a, b, (d, e) -> d < e); // true if a is less than b
点赞
评论