• ### Popular Now

• 11
• 9
• 12
• 9
• 11

#### Archived

This topic is now archived and is closed to further replies.

# [java] Calling java functions using a String var?

This topic is 5116 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''m writing this program where the user can use a console window to input simple commands, these commands will be parsed and sent to a GrafischeEngine Object (the graphical engine). Now I want this parsing to be easily extendable, so I made myself a static final Object array that holds the commands, followed by the number of parameters this command requires. The reason I handled it like that is so that I can easily add commands at the end of that array, without having to write another if else structure. My parse method is given a String (that is the command AND the parameters), I check to see if this is a known command (after trimming spaces from the string)and then we get to the point where I need a bit of help. The commandnames are also engine functions, so what I would like to do is, call that GrafischeEngine function using the String that is in that Object array. For example
GrafischeEngine engine;
static final Object ar={"foo",new Integer(2)};
//suppose the command String is "foo 1 3"
//we found it in ar, so lets run whatever it is we found
System.runFunction(engine,"foo",1,3);
//I made that function up, but I want to do something similar

With a bunch of error checking of course, and I guess I''ll have to add the type those parameters have to be to the array aswell. I just want to avoid writing a bunch of if else''s and have it easily extendible, but if I have to I will. I ran a search on google, and checked the java tutorial, but I haven''t found anything (just native language method calling, and frankly I have no idea what''s it called I''m looking for). Although English is not my first language, I still hope you guys/girls understood what I''m trying to say/do here.

##### Share on other sites
I think what you want to do is supported by the Java reflection API. Here is a pretty good intro to reflection in Java. In particular this page shows how to invoke a method based on string that contains the method''s name.

##### Share on other sites
Thanks alot SiCrane, that''s exactly what I was looking for!
You guys sure are fast around here