I am new to Java 8 and wanted to know if it is possible to pass instance methods to another method, which in turn calls it using the lambda parameter:
Consider this class:
import java.util.function.Predicate;
public class PredicateTest {
private class SomeType {
public boolean bar() {
return true;
}
public boolean foo() {
return true;
}
}
public void someMethod() {
Predicate<SomeType> firstPredicate = someType -> someType.bar();
Predicate<SomeType> secondPredicate = someType -> someType.foo();
}
public Predicate<SomeType> getGenericPredicate() {
Predicate<SomeType> predicate = someType -> someType.
return predicate;
}
}
The someMethod()two predicates are created SomeType.
If SomeTypeit has 20 methods, perhaps we need to write 20 similar predicates.
I am wondering if it is possible using Java 8 to avoid code duplication using a type method getGenericPredicatethat can take bar()either foo()as a parameter and returns the correct predicate.
The goal is to reorganize someMethodinto something like this:
public void someMethodRefactored() {
Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar());
Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo());
}