1

I am making a chat. and i have everything working. But i would like to implement commands that the user can run by typing / then the command. I was thinking i would test for the '/' char at index 0. And if thats true i would run that "code". So the user would essentially be calling a method. but i cant figure out how to convert the string into java code. Help would be appreciated. And if anyone has an easier method of how to implement commands feel free to let me know.

Where

String userinput = "/test()";

Thanks

2 Answers2

3

Letting the user actually run code via his input would require 'reflection' (you will find a lot about this by just googling e.g. 'java reflection').

BUT ATTENTION: Letting the user execute Java code this way is a big security problem!

I think the better approach for you would be something like this:

public void executeUserCommand(final String userInput) {

    String commandFromUser = // parse fromUserInput
    String param = // parse fromUserInput


    switch (commandFromUser) {
        case "command1":
            // call method with 'param'
            break;
        case "command2":
            // call method with 'param'
            break;

        default:
            // tell the user that his command was not found
            break;
    }

}
Sebastian
  • 429
  • 2
  • 8
  • 17
0

You're going to need to look into the Java reflection API to really do anything more than very basic stuff.

At a high level, what I would do is something like this:

/test

or

/msg "John Smith" "XYZ"

You can then parse that into three tokens which gives you msg and two parameters.

What you'll want to do is use reflection to look at the object that handles the chat functions and look up any method named msg that takes two String paramters.

If you decide that allowing numbers and booleans and such is going to be part of it, you're going to get into the weeds pretty fast with the parsing side so be aware of that.

Update: saw this:

"/rep(5,"Hello");

That's going to be a lot harder to parse than /rep 5 "Hello" or /rep 5, "Hello"

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83