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
kll
August 8, 2019, 10:12am
3
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
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
1 Like
kll
August 8, 2019, 10:58am
6
thanks for adding some context info, can’t wait to see your full project here.
Internally, method PApplet ::thread() invokes method PApplet ::method() :
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 :
method("myProcedure");
public void method(String name) {
try {
Method method = getClass().getMethod(name, new Class[] {});
method.invoke(this, new Object[] { });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
} catch (NoSuchMethodException nsme) {
System.err.println("There is no public " + name + "() method " +
"in the class " + getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
3 Likes
Some silly examples below just to give an idea on how dynamic calls can be useful for some cases:
3 Likes
Thank you! you are very helpful!