Create callback

If you need to know whether 2 Method objects represent the same actual method, just call equals() on 1 of the objects in order to compare them. :bulb:

You can also call getParameterTypes() to get an array of classes of the Method’s parameter types: :smile_cat:

Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Executable.html#getParameterTypes()

// https://Discourse.Processing.org/t/create-callback/9831/20
// GoToLoop (2019/Apr/05)

import java.lang.reflect.Method;

final Method[] methods = {
  getMethod("myMethod", this, String.class, int.class), 
  getMethod("myMethod", this, String.class, int.class), 
  getMethod("myMethod", this, String.class, int.class, float.class)
};

void setup() {
  println(methods[0] == methods[1]); // we can't use the compare == operator!
  println(methods[0].equals(methods[1])); // true
  println(methods[0].equals(methods[2])); // false

  for (final Method m : methods) {
    println();
    printArray(m.getParameterTypes());
  }

  exit();
}

static final void myMethod(final String stuff, final int num) {
  println(stuff, num);
}

static final void myMethod(final String stuff, final int num, float frac) {
  println(stuff, num);
}

@SafeVarargs static final Method getMethod(
  final String name, final Object instance, final Class... classes) {
  final Class<?> c = instance.getClass();

  try {
    return c.getMethod(name, classes);
  } 
  catch (final NoSuchMethodException e) {
    try {
      final Method m = c.getDeclaredMethod(name, classes);
      m.setAccessible(true);
      return m;
    }   
    catch (final NoSuchMethodException ex) {
      ex.printStackTrace();
      return null;
    }
  }
}