I've below requirement:-
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");
}
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.
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();;
}
}
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.
Predicate interface has method test()
. You should use this method in a following way:
isAdult.test(age)
This method evaluates this predicate on the given argument. It returns true if the input argument matches the predicate, otherwise false
This looks a little bit suspicious, you care if the employee is an adult, so your method should really take a Employee
as an argument and a Predicate<Employee>
, like this:
private static void testEmployee(Employee emp, Predicate<Employee> predicate) {
boolean result = predicate.test(emp);
System.out.println(result);
}
And the usage of this method would be:
testEmployee(new Employee(13), emp -> emp.isAdult(emp.getAge()));
The thing is you can reuse this method for other predicates as well, let's say you want to test gender, or income, etc.
Predicate has test method, that is used, when working with streams/optionals.
public PredicateAnotherClass(Integer age, Predicate<Integer> isAdultFilter) {
this.age = age;
System.out.println("Test result is "+ isAdultFilter.test(age));
}
来源:https://stackoverflow.com/questions/44583847/java-use-predicate-without-lambda-expressions