I am about to begin coding a demo program for a lecture I'm about to give. I want to let each student in the class download this application, then be able to create instances of objects (and their graphical representations) interactively via a command line. I decided to write in java, not because it's the language I'm most familiar with, but because it's got easy graphics classes and I can be pretty sure that the jar is going to run on their computers.
Intro over. Now the question:
What is a good way to implement some custom command line syntax for this program? I want to use a simple, arbitrary syntax like:
CREATE Monster Bob;
Bob.jump();
LS Bob //to list Bob's methods or something.
LS CREATE //to list all the classes
First I'll spiel about what first came to mind when I thought of this problem.
I can imagine that I could have a set of maps in a tree type linkage. I could parse each key word as the key to the next map. So "CREATE Monster Bob" could be evaluated like
1) Search keyword map for key "CREATE". Return the value, which is a reference to the map of classes.
2) Search classes map for key "Monster". Return the value, which is a factory class implementing some interface Leaf that lets me know it is a leaf value (I'll check using instanceof).
3) Maybe the Leaf interface will contain a method called execute() that will do whatever it wants. In this case it would create an object of Monster, adding this object to a map called Objects with the name Bob. (This Leaf business sounds ugly but it could be cleaned up.)
Cool. But this statement is a little harder for me: Bob.jump();
1)Search some map of objects for "Bob". Return some object implementing an interface with a method like "evaluate(String s)" and pass it the string "jump()"
2)Bob searches some internal map of methods for "jump()", then...? In c++ I would have the key be a pointer to the member function Monster.jump() which would be executed. But there is no such thing as a function pointer in java I don't believe. I have read you can use an anonymous class to accomplish this, though I haven't tried. Looks like it would work.
So, this will work, but is there a more elegant way to go about this? I've never written any type of interpreter before. I'd like to do it a nice way and learn something in the process if somebody has some tips. This seems like a potentially error prone way to do things if I'm not very structured, especially when Bob and every other object start parsing their own instructions and using anonymous functions. In addition, it looks like every class will need a runtime-ready interface besides its normal code.
I also don't know Java all that well, so if there are some spots where I might hit a brick wall, then I'd like to know too.
Thanks for the help in advance.