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.
A very good way of doing this apart from using Java 7 is using enums. Declare enum as shown below
The above enum has a collection of constants whose values are set to the strings that you expect would be returned from the database. As you can use enums in switch cases the remaining code becomes easy
All you have to do is pass your string to the enum.valueof method and it will return the appropiate enum which is put in a switch case block to perform conditional operation . In the above code you can pass any string in place of what is passed in this example
This doesn't answer your question per se; it offers an alternate solution that may effect the same result.
Instead of storing a single database column with pseudocode that defines a condition, make a table in which the schema define types of conditions that must be satisifed and the values of those conditions. This simplifies programmatic evaluation of those conditions, but it may become complicated if you have a variety of types of conditions to evaluate.
For example, you might have a table that looks like the following.
Those row entries, respectively map to the rules
value > 2
and6 > value > 4
.This confers a number of benefits over the approach you provide.
Here is an example using the standard (Java 1.6+) scripting library:
For evaluating the conditions with maximum flexibility use a scripting language designed for embedding, for instance MVEL can parse and evaluate simple conditional expression like the ones in the question.
Using MVEL has one huge advantage over using the Scripting engine in Java 1.6+ (in particular, with JavaScript): with MVEL you can compile the scripts to bytecode, making their evaluation much more efficient at runtime.
It's not going to be trivial: you need a parser for the expression language used in your database. If it's some standard, well-specified language, then you might be able to find one on the Internet, but if it's an in-house thing, then you may need to write your own (perhaps using a parser generator like ANTLR.)
The javax.script package contains some tools for integrating external scripting engines like a Javascript interpreter. An alternative idea would be to bring in a scripting engine and feed the expressions to that.
The latest version of java (Java 7) allows Switch Case statements on Strings, if there are not many possible variations you could just do this or similar :