Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition String Resolver in java API? [closed]

Tags:

java

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
like image 645
Zaw Than oo Avatar asked Dec 27 '13 07:12

Zaw Than oo


2 Answers

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
like image 177
René Link Avatar answered Sep 18 '22 02:09

René Link


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

EXAMPLE

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
like image 43
Prateek Avatar answered Sep 21 '22 02:09

Prateek