[java] Calling java functions using a String var?

Started by
2 comments, last by BertS 19 years, 12 months ago
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.
Advertisement
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.
Thanks alot SiCrane, that''s exactly what I was looking for!
You guys sure are fast around here
You might also want to look into the Command pattern (although the variable-arguments thing will make life difficult for you... of course, you can always generalize your arguments to Object[]) - you can have a HashMap mapping command Strings to corresponding Executable objects, do a lookup with part of the input, and .execute() the resulting object with arguments coming from the rest of the input.

This topic is closed to new replies.

Advertisement