Call a procedure by its name in String

Ok, so you can do like

thread("myProcedure");

but it creates a new thread.
Is it possible to call a procedure in a similar way it the main thread?
Or even maybe there is a way to execute code in a String? Like

String changeColors = "fill(200); \n stroke(100);";

execute(changeColors);
1 Like

Yes you can!

String methodName = "meh";
void setup(){
  raiseEvent(methodName);
}

void meh(){
  println("Hello!");
}

void callByName(Object obj, String funcName) throws Exception {
  obj.getClass().getDeclaredMethod(funcName).invoke(obj);
}

void raiseEvent(String funcName) {
  try {
    callByName(this, funcName);
  } 
  catch (Exception ex) {
    ex.printStackTrace();
  }
}

If you want to pass the arguments, it lil bit complicated
further read: reflection - How do I invoke a Java method when given the method name as a string? - Stack Overflow

3 Likes

and why you need this ( compared to a function (call ) )

Thank you very much, humayung!

if you can’t imagine why you need this you probably don’t want this :slight_smile:

well, for creating a GUI, for example. you declare a gui element class having a String methodName which you’d call when mousePressed or keyPressed or whatever. so the class method executes a proc by its name and the actual gui element is assigned a real proc name to call when clicked.

thanks for your attention anyway :wink:

1 Like

thanks for adding some context info, can’t wait to see your full project here.

Internally, method PApplet::thread() invokes method PApplet::method(): :thread:
Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html#method-java.lang.String-

And we can do the same if we don’t need it to be run in another Thread: :smile_cat:
method("myProcedure");

3 Likes

Some silly examples below just to give an idea on how dynamic calls can be useful for some cases: :flushed:

3 Likes

Thank you! you are very helpful!