Search code examples
javarule-enginemvel

Evaluate Json based Rule at runtime in Java


I have a requirement to convert rules present in json format in database to code in Java at runtime.

For example,

{
  "id": "g-KqVJwrEMUYNOEVEnNxxqc",
  "rules": [
    {
      "id": "r-2VC4YQOkYu-lxkGgMABRc",
      "field": "firstName",
      "value": "Steve",
      "operator": "="
    },
    {
      "id": "r-B2Dd6eHO1rsZ-t1mfPk33",
      "field": "lastName",
      "value": "Vai",
      "operator": "="
    }
  ],
  "combinator": "and",
  "not": false
}

The keys in the json will be known before hand. Also the fields and operator values will be fixed and known.

But I am puzzled as to how to convert something like the one above to code,

inputObject.firstName.equals("Steve") && inputObject.lastName.equals("Vai")

Any leads, thoughts is highly appreciated!


Solution

  • You can use introspection to evaluate fields at runtime

    It would look something like this

    Command command = parseJson(input); // transform input into a java object
    InputObject o = getItFromSomewhere();    
    bool finalResult;
    
    
    // process each rule
    for ( Rule r: command.rules ) {
    
       var fieldValue = o.getClass().getField(r.field).get(o);
    
       var currentResult;
       switch(r.operator) {
          case "=": currentResult = fieldValue.equals(r.value);
          break;
          case ">": currentResult = .... 
          ..etc
        } 
    
        // combine it with previous results; 
        switch(command.combinator) {
          case "and": 
             finalResult = finalResult && currentResult;
             break;
           case "or":
              finalResult = finalResult || currentResult;
         }
    
    }
    System.out.println(finalResult);
    

    Obviously this is not the exact code but just to show how to retrieve dynamically a field value at runtime and evaluate it.