I would like to resolve the following condtion string. Because I would like to support dynamic condtion in my project.
a != 0 && b > 5
My expected Program is
public boolean resolve() {
String condition = "a != 0 && b > 5";
Map<String, Object> paramMap = new HashMap<String, Object>;
paramMap.put("a", 2);
paramMap.put("b", 6);
boolean result = ConditionResolver.resolve(condition, paramMap);
if(result) {
//do something
}
}
Update :
I am not trying to resolve the math equation, like below
((a + b) * y) /x
As of java 1.6 you can use the ScriptEngine
and evaluate javascript if this is enough for you and/or if you don't want to introduce another library.
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("javascript");
SimpleBindings bindings = new SimpleBindings();
bindings.put("a", 0);
bindings.put("b", 6);
boolean firstEval = (Boolean) scriptEngine.eval("a != 0 && b > 5", bindings);
System.out.println(firstEval);
bindings.put("a", 2);
bindings.put("b", 6);
boolean secondEval = (Boolean) scriptEngine.eval("a != 0 && b > 5", bindings);
System.out.println(secondEval);
Output
false
true
I think you should use expression libraries.May be this post will help you Built-in method for evaluating math expressions in Java
For Evaluating Logical Expressions refer following library : JANINO
import java.lang.reflect.InvocationTargetException;
import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.ExpressionEvaluator;
public class WorkSheet_1{
public static void main(String[] args) throws CompileException, InvocationTargetException {
ExpressionEvaluator ee = new ExpressionEvaluator(
"a != 0 && b > 5",
boolean.class,
new String[] { "a", "b" },
new Class[] { int.class, int.class }
);
Boolean res1 = (Boolean) ee.evaluate(new Object[] {new Integer(2), new Integer(6),});
System.out.println("res1 = " + res1);
Boolean res2 = (Boolean) ee.evaluate(new Object[] {new Integer(2), new Integer(5),});
System.out.println("res2 = " + res2);
}
}
OUTPUT
res1 = true
res2 = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With