Java: create logical expressions and then test them

I have a little functionality where I need to determine if a user-created rule is syntactically valid.

We believe that the structure of what I create is as follows:

  • 1 == 1
  • 1 + 1 == 1
  • 1 + 1 == 1 OR 1 == 1
  • Additional combinations of the above examples

These expressions are stored in a string variable, for example:

String expression = "";

while(items.hasNext())
{
    String currentItem = items.next();
    expression += currentItem.value();
}

//Check if the expression is valid

REAL EXPRESSIONS

Valid expressions are those that have a logical operator (<, <=, ==, =>,>), and the output will be true or false (it does not matter which one)

  • 1 == 1
  • 1 <2
  • 1 == 1 OR 1 <4
  • 4 == 9 OR 9 == 3

WRONG EXPRESSIONS

Invalid expressions are those that do not have the proper structure to determine if this expression is true or false.

  • 1
  • 1 + 1
  • 1 ===
  • == 1
  • 1
  • 11 ( , )

Boolean.valueOf()

Boolean.parse()

+4
1

- .

EDIT2 , .

import javax.script.ScriptEngineManager;
import javax.script.*;

public class HelloWorld{

    public static void main(String[] args) 
    {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        String expression = "1+2";   // evaluates to Failure: 3
        String expression = "1+a";   // evaluates to Failure:
        String expression = "1==1";  // evaluates to Success: true
        String expression = "1==2";  // evaluates to Failure: false
        try
        {
            Object result = engine.eval(expression);

            if(result instanceof Boolean)
            {
                System.out.print("Success: ");
                System.out.println(result);
            }
            else
            {
                System.out.print("Failure: ");
                System.out.println(result);
            }
        }
        catch(ScriptException e)
        {
            // handle
            System.out.println("Failure");
        }
    }
}

https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html

https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html

+4

All Articles