Reflections and console

Hello,
I’ve made this in c# before and I’d like to know, how to do this in Java.
I have a set of commands with arguments i.e.

//Command: "set var <string:name> <int:value> <bool:log>"
string[] commandName = new string[]{"set", "var"};
Type className = AriaVar.getType();
String methodName = "setVar";
string[] argumentTypes = new string[]{"string", "int", "bool"};

AriaCommandBlueprint acb = new AriaCommandBlueprint(commandName, argumentTypes, className, methodName);

A console will take a user input and run a method methodName in class type with arguments argumentTypes. I’d like to do this in Java, possibly inside Processing’s PApplet.

Hi. i hope this well work.

`String[] commandName = {"set", "var"};
String methodName = "setVar";
String [] argumentTypes = {"string", "int", "bool"};

String className = this.getClass().getSimpleName();

AriaCommandBlueprint acb = new AriaCommandBlueprint(commandName, argumentTypes, className, methodName);

You can use Java reflection.

Method method = getClass().getDeclaredMethod("name", String.class); // gets method "name" with a String argument
method.invoke(this, "hello"); // invokes the method on this object with the argument "hello"

Using this knowledge you may have a console command like set hello 2. We can use it in our command parser:

String cmd = "set hello 2";
String[] args = cmd.split("\\s+"); // we use a regular expression that can detect more than one space
Method cmdMethod = getClass().getDeclaredMethod("cmd_" + args[0], String[].class); // I don't remember the exceptions this method throws, you'll have to find out yourself
cmdMethod.invoke(this, args); // I don't remember the exceptions of this either

// then we can have a method like
void cmd_set(String[] args) {
  // do something
}

That method will be then called each time you use the command set.

Processing provides methods method() & thread() too. :sunglasses:
Plus the args[] array w/ the strings passed when running the sketch. :running_man: