有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java使用不带lambda表达式的谓词

我有以下要求:-

员工。java

public boolean isAdult(Integer age) {
    if(age >= 18) {
        return true;
    }
    return false;
}

谓词。java

    private Integer age;
Predicate<Integer> isAdult;

public PredicateAnotherClass(Integer age, Predicate<Integer> isAdult) {
    this.age = age;
    System.out.println("Test result is "+ isAdult(age));
}

public void testPredicate() {
    System.out.println("Calling the method defined in the manager class");

}

现在,我的目标是测试我传递给Predicate年龄是否是成年人,是否使用Employee类中定义的方法,为此,我传递在Predicate类的构造函数中传递的方法引用

但是我不知道如何调用Employee类中定义的方法,下面是我的测试类:-

public class PredicateTest {

    public static void main(String[] args) {
        PredicateManager predicateManager = new PredicateManager();

        PredicateAnotherClass predicateAnotherClass = new PredicateAnotherClass(20, predicateManager::isAdult);
        predicateAnotherClass.testPredicate();;
    }
}

我在predicate类的System.out.println("Test result is "+ isAdult(age));中得到编译错误

让我知道如何解决这个问题。如果我需要提供任何其他信息


共 (3) 个答案

  1. # 1 楼答案

    谓词具有在处理streams/optionals时使用的测试方法

    public PredicateAnotherClass(Integer age, Predicate<Integer> isAdultFilter) {
        this.age = age;
        System.out.println("Test result is "+ isAdultFilter.test(age));
    }
    
  2. # 2 楼答案

    谓词接口具有方法test()。应按以下方式使用此方法:

    isAdult.test(age)
    

    此方法对给定参数计算此谓词。如果输入参数与谓词匹配,则返回true,否则返回false

  3. # 3 楼答案

    这看起来有点可疑,如果员工是成年人,您需要关心,因此您的方法应该将Employee作为参数,将Predicate<Employee>作为参数,如下所示:

     private static void testEmployee(Employee emp, Predicate<Employee> predicate) {
        boolean result = predicate.test(emp);
        System.out.println(result);
    }
    

    这种方法的用途是:

    testEmployee(new Employee(13), emp -> emp.isAdult(emp.getAge()));
    

    问题是,您也可以对其他谓词重用此方法,比如说您想要测试性别或收入等