1

I need to write a java program which reads rules (conditions) from a file. The rules have to be transformed as conditions in Java. I don't know how to transform the rules specified as strings to Java source code.

For example, the rules like:

x != y

or

n >= 0 && s == n 

should be transformed to Java source code as:

if(x != y){......} else{....}

How can I made this possible?

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
code4fun
  • 1,012
  • 3
  • 24
  • 41
  • 5
    Generally speaking, with a parser. Your question does not provide enough information to help further. What have you tried so far? – Darth Android Mar 25 '16 at 16:16
  • I've used the `ScriptEngine` class for something like this in the past. That class lets you load JavaScript from an external source and execute it within the context of your Java program. Within the JavaScript code, you can create Java objects and execute methods on those objects almost exactly as you would in Java. That might be an alternative to trying to parse strings. – Cypher Mar 25 '16 at 16:22
  • Yes it's possibile duplicate. I will try the solution of eval() and let you know. – code4fun Mar 25 '16 at 16:23
  • If you really want to generate source code, you could just print java source text interleaved with the text of your rules. That's a pretty shaky foundation, because there is no way to know if the generated text makes any sense at all. You can also consider more sophisticated code generation schemes that operate over well-formed code elements. See http://stackoverflow.com/a/28103779/120163 – Ira Baxter Mar 25 '16 at 19:16
  • ... if all you want to do is evaluate some conditions are runtime, you'll need to parse the condition text and evaluate it. This series of SO posts tells you how to build parsers (esp. appropriate for simple expressions) and how to build interpreters for such parsed results: http://stackoverflow.com/a/2336769/120163 – Ira Baxter Mar 25 '16 at 19:23

2 Answers2

0

May be my answer looks like a cannon against sparrow, but look at JRule the engine that allows you create flexible system of business rules inside java application

Dewfy
  • 23,277
  • 13
  • 73
  • 121
0

Another option is Jess. I've used it in the past with good success for handling rules-based activities.

KevinO
  • 4,303
  • 4
  • 27
  • 36