Calling functions with variables

This might be a somewhat more efficient and safer approach, although it probably doesn’t matter too much:

import java.lang.reflect.*;

Method[] scenes;

void setup() {
  scenes = getMethodsStartingWith("scene");
}

void draw() {
}

Method[] getMethodsStartingWith(String prefix) {
  try {
    ArrayList<Method> list = new ArrayList<Method>();
    Method[] all = getClass().getDeclaredMethods();

    for (Method method : all)
      if (method.getName().startsWith(prefix))
        list.add(method);

    return list.toArray(new Method[0]);
  } catch (SecurityException e) {
    e.printStackTrace();
  }

  return new Method[0];
}

void mousePressed() {
  try {
    scenes[int(random(scenes.length))].invoke(this);
  } catch (ReflectiveOperationException e) {
    e.printStackTrace();
  }
}

void scene1() {
  print(1);
}

void scene2() {
  print(2);
}

void scene3() {
  print(3);
}

Instead of having to find the method and thereby risk getting an exception and wasting time every mouse press, this code only searches through all the methods once and then stores the ones we need in an array.

The downside to this is of course that it’s not as clean as just doing method(...) and since it has to search through all methods in the beginning (which I suspect PApplet has a lot of) while method(...) probably just calls getMethod(name) behind the scenes, I’m not sure how often mousePressed has to be called for this version to be better than the other.

2 Likes