Java-使用不带lambda表达式的谓词 [英] Java - Use predicate without lambda expressions

查看:104
本文介绍了Java-使用不带lambda表达式的谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我符合要求:-

Employee.java

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

Predicate.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");

}

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

Now My goal is to test whether the age which i pass to Predicate is adult or not using the method defined in Employee class , for which i am passing the method reference which i pass in the constructor of Predicate class.

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

But i don't know how to call the method defined in Employee class, below is my test class :-

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));中遇到编译错误.

I am getting the compilation error in the System.out.println("Test result is "+ isAdult(age)); in the predicate class.

让我知道如何解决此问题.以及是否需要提供其他信息.

Let me know how to resolve this issue. and if i need to provide any other information.

推荐答案

谓词接口具有方法test().您应该通过以下方式使用此方法:

Predicate interface has method test(). You should use this method in a following way:

isAdult.test(age)

此方法根据给定参数评估此谓词.如果输入参数与谓词匹配,则返回true,否则返回false

This method evaluates this predicate on the given argument. It returns true if the input argument matches the predicate, otherwise false

这篇关于Java-使用不带lambda表达式的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆