Home > Net >  Translating logic into Kotlin (or Java) code
Translating logic into Kotlin (or Java) code

Time:05-22

I have a use-case where I want to enable users to write simple logic, and behind the scenes, convert this logic into a condition in the code.

For example, the user might write:

someFieldName > 10 AND otherFieldName is NULL

And I'd like that to generate the following code:

if (data["someFieldName"] > 10 && data["otherFieldName"] == null) {
   // Do something
}

After doing some research, I saw that one of the options is using eval (by leveraging a JS engine), although it doesn't fit all use cases. I also saw that it's possible to use tools like ANTLR, which seems a bit like overkill.

Are there any simple off-the-shelf products we can use for such purposes? Or would creating a simple parser ourselves be the best way to handle it?

CodePudding user response:

Your use case can be adequately addressed by MVEL2.

There is no need for you to write a parser and AST with ANTLR or convert to Java code, just evaluate the expression with appropriate parameters.

In fact any Java expression language library would do. You could also look at JUEL.

However, looking at the expression, I would say it aligns more towards MVEL2.

Give both the libraries a try.

  • Related