Create callback

Oh, I was doing almost the same too: :disappointed:

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

import java.lang.reflect.Method;
final Method myMethod = getStrIntMethod("myMethod", this);

void setup() {
  frameRate(1);
}

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

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

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

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

static final void invokeStrIntMethod(
  final Method funct, final Object instance, final String txt, final int val) {
  try {
    funct.invoke(instance, txt, val);
  } 
  catch (final ReflectiveOperationException e) {
    e.printStackTrace();
  }
}
1 Like