Create callback

You can call getStrIntMethod() from anywhere, as long as you have access to the “myMethod”'s object instance reference. :sunglasses:

BtW, here’s a more powerful generic version, which can find & invoke any method name w/ any number of parameters & types: :partying_face:

/**
 * Method Reflective Invocation (v4.0)
 * Stanlepunk (2019/Apr/03)
 * Mod GoToLoop
 * https://Discourse.Processing.org/t/create-callback/9831/16
 */

import java.lang.reflect.Method;
final Method myMethod = getMethod("myMethod", this, String.class, int.class);

void setup() {
  frameRate(1);
}

void draw() {
  background((color) random(#000000));
  invokeMethod(myMethod, this, "Frames:", frameCount);
}

static final void myMethod(final String stuff, final int num) {
  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;
    }
  }
}

@SafeVarargs static final Object invokeMethod(
  final Method funct, final Object instance, final Object... args) {
  try {
    return funct.invoke(instance, args);
  } 
  catch (final ReflectiveOperationException e) {
    throw new RuntimeException(e);
  }
}
1 Like