I have a method let's say in ClassA
. I want to pass a method from ClassB
as an argument to that method in ClassA
. In this case I want to pass the getCode
method from ClassB
. I don't have any instance of ClassB
and I'd like to achieve this without having to create one.
I've tried using simple method reference, but it does not work this way. I don't want to make getCode a static method either.
public class ClassA {
public void validate() {
Validation validation = new Validation(ClassB::getCode, code);
//...
}
}
My final goal is to have a RequestValidator class to which add validations, each validation will be created with a specific method and a string in its constructor, in this case getCode from classB and code. Please note I only want one instance of RequestValidator. Something like this:
RequestValidator validator = new RequestValidator<>()
.addValidation(new Validation(ClassB::getCode, code))
.addValidation(new Validation(ClassB::getName, name));