How pass methods as parameters in Java using method reference notation (Class::method)?

Viewed 70

I want to create method in a Utils class that accepts two parameters, the first is the domain class, and the second is a method from the domain class (passed as reference). This Utils' class has a method that will create an instance of the class and execute the method in the scope of the domain class instance.

For example, the domain class:

public class DomainClass {
  
  public void dummyMethod() {}
  
}

The Utils class:

public class Utils {

  public static void execute(Class<?> clazz, Runnable referenceMethod) {
     Object objInstance = clazz.getConstructor().newInstance();
     // execute the 'referenceMethod' on the scope of 'objInstance'
  }

}

The call I want is something like: Utils.execute(DomainClass.class, DomainClass::dummyMethod). However, this scenario has some problems:

  1. How can I pass this parameters for the Utilsclass (now I'm having some compilation problems)?
  2. How can I call the 'referenceMethod' with the scope of 'objInstance'?
1 Answers

DomainClass::dummyMethod is a reference to an instance method, and you need to provide an object instance to run it. This means it cannot be a Runnable, but it can be a Consumer for example.

Also, it will help to make the execute method generic:

    public static <T> void execute(Class<T> clazz, Consumer<T> referenceMethod) {
        try {
            T objInstance = clazz.getConstructor().newInstance();
            referenceMethod.accept(objInstance);
        } catch (Exception e) {
            e.printStackTrace();
        }
   }

Now you can call execute like this:

    Utils.execute(DomainClass.class, DomainClass::dummyMethod);
Related