Search code examples
javastringif-statementbooleanevaluate

Evaluate command line argument as boolean expression


I'm trying to take a string, passed as an argument, and evaluate it as a boolean expression in an if conditional statement. For example, the user invokes MyProgram like $ java MyProgram x==y.


Example Program

Defined variables:

int x;
int y;

Boolean expression argument:

String stringToEval = args[0];

Control program execution with user expression:

if (stringToEval) {
    ...
}

Solution

  • You'll need to use some form of expression parser to parse the value in args[0] and create an expression that can be applied to x and y. You may be able to use something like Janino, JEXL or Jeval to do this. You could also write a small parser yourself, if the inputs are well-defined.