We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello I have a question, one class has a field of type String and I want to call a function that is called as the content of this string, someone can help me with the code? I looked reflection and I have recommended it but I can not see anything clear ..
I leave an example of what I want to do but using the content of the string.
//Global var block..
tt myTest;
void setup(){
size(640, 400, P2D);
frameRate(60);
myTest = new tt("function1");
}
//...................................................
void draw(){
myTest.executeExternalFunctionByName();
}
//...................................................
class tt{
String name = "";
// constructor..
tt(String name_){
name = name_;
}
// internal functions..
void executeExternalFunctionByName(){
function1(); // this is the problem!
}
}
//...................................................
// External funcion..
void function1() {
println("External function has executed!");
}
Answers
http://forum.Processing.org/two/discussion/8045/how-to-format-code-and-text
Use method("")! Called function gotta reside outside any class though.
That is, it needs to be a sketch function. :-B
OMG!!!! Thank you!!! Thank you!!! Thank you!!!
You can pass parameters in this way?
Unfortunately neither method("") nor thread("") allow parameters.
We'd have to rely on "global" variables for it. :-S
Thank you man!!
Very true, if we want parameters we have to do it ourselves.
The following code demonstrates one way to do it. If you run the code you will see that it handles parameterless methods as well :)
Notice that instead of
int
you have used the class equivalentInteger
, this applies to all the primitive typesJava has 8 primitive datatypes and 8 corresponding wrappers.
You've listed 7. But forgotten
byte
-> Byte. ;;)And although it doesn't seem like, we can have Class primitives too! @-)
Class myPrimitiveInt = int.class;
@GoToLoop well down on the
int.class
I had completely forgotten about that.So I take back what I said about using the class equivalents for primitives and here is the adapted code
Congratz! Nice utility class! :-bd
Just 1 detail more: "parameterless" execute() method isn't necessary at all! >-)
And of course, it's futile to use
private
on those field members. >:)Well done again - true on both counts. It was cobbled together from a top-level class I use in G4P hence the private access specifiers.
thank you both, this information is very good!