3

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'?
João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25

1 Answers1

7

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);
Joni
  • 108,737
  • 14
  • 143
  • 193
  • Could you explain the reason why this work? I've seen this tutorial from [MKYong](https://mkyong.com/java8/java-8-consumer-examples/) and it don't bind with what you showed me. – João Pedro Schmitt Aug 24 '20 at 16:51
  • 2
    It's a "Reference to an Instance Method of an Arbitrary Object of a Particular Type" there's a short description in the official tutorial https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html and a longer discussion with this stackoverflow question https://stackoverflow.com/questions/23533345/what-does-an-arbitrary-object-of-a-particular-type-mean-in-java-8 – Joni Aug 24 '20 at 16:57