Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate String as a condition Java

Tags:

I have to retrieve a set of column values from D/B and check it as a condition.

For example, I will have strings like "value > 2", "4 < value < 6" in a D/B column. (value is the one which is compared all the time). I will have a variable value declared in my code and I should evaluate this condition.

int value = getValue(); if (value > 2)  //(the string retrieved from the D/B)   doSomething(); 

How can I do this?? Any help is muceh appreciated. Thanks.

like image 279
Venkateshwarrao Surabhi Avatar asked Jun 06 '12 16:06

Venkateshwarrao Surabhi


People also ask

How are if conditions evaluated in Java?

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1. 8). If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.


2 Answers

Here is an example using the standard (Java 1.6+) scripting library:

import javax.script.ScriptEngine; import javax.script.ScriptEngineManager;  public class Test {      public static void main(String[] args) throws Exception {         ScriptEngineManager factory = new ScriptEngineManager();         ScriptEngine engine = factory.getEngineByName("JavaScript");          engine.eval("value = 10");         Boolean greaterThan5 = (Boolean) engine.eval("value > 5");         Boolean lessThan5 = (Boolean) engine.eval("value < 5");          System.out.println("10 > 5? " + greaterThan5); // true         System.out.println("10 < 5? " + lessThan5); // false     } } 
like image 63
assylias Avatar answered Oct 30 '22 21:10

assylias


You are basically evaluating a scripted expression. Depending what is allowed in that expression, you can get away with something very simple (regular expression identifying the groups) or very complex (embed a javascript engine?).

I'm assuming you're looking at the simple case, where the expression is: [boundary0] [operator] "value" [operator] [boundary1]

Where one, but not both of the [boundary] [operator] groups might be omitted. (And if both are presents, operator should be the same)

I would use a regular expression for that with capturing groups.

Something like: (?:(\d+)\s*([<>])\s*)?value(?:\s*([<>])\s*(\d+))?

And then: boundary1 = group(1); operator1 = group(2); operator2 = group(3); boundary2 = group(4)

like image 29
ptyx Avatar answered Oct 30 '22 20:10

ptyx