1

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));
rubydio
  • 105
  • 2
  • 7

2 Answers2

0

getCode needs to be a static function, and the syntax would be ClassB.getCode. You would need ClassB to be imported into ClassA.

See:

Calling static method from another java class

w8std
  • 24
  • 2
0

Your use of a method reference will work just fine as long as you define the method arguments properly. You haven't given a lot of information, so I'm going to make some assumptions here. Please correct me if this isn't what you had in mind:

public class B { 
  public static String getCode() {
    return "foobar"; // Replace with your own functionality
  }
}

public class Validation {
  Validation(Supplier<String> supplier, String code) {
    String suppliedCode = supplier.get();
    // Do your validation logic
  }
}

public static void validate() {
  Validation validation = new Validation(ClassB::getCode, code);
}

But this frankly feels like overkill. Why can't you just make your Validation constructor take two String arguments (or whatever types you happen to be using), and then do this?

public static void validate() {
  Validation validation = new Validation(ClassB.getCode(), code);
}

Do you have a legitimate need to pass in a method reference instead of simply passing in the return value from the method call?

Jordan
  • 2,273
  • 9
  • 16
  • Yeah I'll explain a bit more, I have a RequestValidator class and what I want is to add validations to that class, each validation will be created with a specific method and a string, 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));``` – rubydio Jun 11 '19 at 06:44