Hello.
I am trying to do a very simple command line library for interactive Java programs. You start the Java program and it prompts you for commands. The syntax is:
> action [object_1, [object_2, [... object_n] ... ]]
for example:
> addUser name "John Doe" age 42
Here action = "addUser", object_1 = "name", object_2 = "John Doe", object_3 = "age", object_4 = "42"
.
Everything after action is an object (that is, an action uses objects). You can see that the action and the object are simple strings. Object strings can also be converted to numbers if necessary.
My plan is that the user of this command line library would simply create methods (belonging to any suitable Java object) and assign each method to a specific action. The objects in the command line become parameters for the method the user assigns. A suitable class that implements a method for the example above would be:
class Foo {
public void addUserHandler(
String param1, String param2, String param3, Integer param4) {
do.someThing();
}
}
When a user types a command, the corresponding function assigned by the programmer gets called with the parameters specified in the command line.
I know that Java doesn't have function pointers (like C) or delegates (like C#) and the way to implement callbacks is through an interface, however, I don't see how can I use interfaces in this scenario. The problem I see with interfaces is that they have:
- A fixed number of functions to be implemented
- The functions to be implemented have a fixed declaration.
The problem with (1) is that the user of my library may decide to implement any number of functions, for as many actions as he wants to support. The problem with (2) is that the user would want to assign functions with descriptive names, like addUserHandler() for "addUSer" action.
If Java had delegates or function pointers I would just create a Map between Strings (representing actions) and delegates (for the actual implementation of the action in the program). I think I can emulate delegates with Reflection, but it is gory and I lose the type safety, as I'd have to use String names for classes and methods. Is there any better way?
Thanks,