Create callback

GoToLoop is providing alternative code to do the same job, whether you use it or not is up to you. There is little to choose between them.

Personally I would stick with the style you are using, there are some benefits to instantiating a Class array to hold the parameter types and separating the catch clauses gives you the option to treat the exceptions differently.

Yes it works but it has one serious flaw, the draw() method is executed 60 times a second but you only need to find the method once.

In the example sketch below I have modified your code so that the method is found in setup and then invoked in draw. It also shows how to find methods without parameters.

import java.lang.reflect.*;

Method method_1 = null;
Method method_2 = null;

void setup() {
  // Find a callback with 2 parameters
  method_1 = select_callback("my_method_1", this, new Class[] {String.class, int.class} );
  // Find a callback with no parameters
  method_2 = select_callback("my_method_2", this, new Class[0]);
}

int count = 0;

void draw() {
  count++;
  try {
    method_1.invoke(this, "truc", count);
  } 
  catch (IllegalAccessException iae) {
    System.err.println(method_1.getName() + "() must be public");
  }
  catch (InvocationTargetException ite) {
    System.err.println("The method " + method_1.getName() + "() threw an exception");
    ite.printStackTrace();
  }

  try {
    method_2.invoke(this);
  } 
  catch (IllegalAccessException iae) {
    System.err.println(method_1.getName() + "() must be public");
  }
  catch (InvocationTargetException ite) {
    System.err.println("The method " + method_1.getName() + "() threw an exception");
    ite.printStackTrace();
  }
}

/**
 Find a method matching the parameters
 @parameter callbackMethod the name of the callback method
 @parameter callbackObject the object resposible for executing the calback
 @parameter params an array of classes of the parametrs for the call back method
 */
Method select_callback(String callbackMethod, Object callbackObject, Class... params) {
  Method callback = null;
  try {
    Class<?> callbackClass = callbackObject.getClass();
    callback = callbackClass.getMethod(callbackMethod, params );
  } 
  catch (NoSuchMethodException nsme) {
    System.err.println(callbackMethod + "() could not be found");
  }  
  return callback;
}

void my_method_1(String stuff, int value) {
  println(stuff, value);
}

void my_method_2() {
  println("============================");
}
2 Likes