-1

Is there any way to make a string as a condtion in java.

Sample is shown below

class A {
    public static void main(String args[]) {

        B b = new B(10, 20);
        b.setCondition("val1>val2");
    }
}

class B {
    int val1 = 0;
    int val2 = 0;

    public B(int v1, int v2) {
        val1 = v1;
        val2 = v2;
    }

    public void setCondition(String condition){
   //the string should be evaluated as conditon like below.
     if(condition) ->  if(val1>val2)

   }
}

Is this is possibility in java. Thank you.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • No, it's not possible, `if` should contain a statement that'll be evaluated to `true` or `false`, not a String. – Maroun Feb 05 '15 at 07:42
  • 2
    possible duplicate of [Is there an eval() function in Java?](http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – Jens Feb 05 '15 at 07:43

2 Answers2

0

You have to implement your own parser, since Java code needs to be compiled. There is no evaluate() method, such as PHP or other scripting languages provide it.

user1438038
  • 5,821
  • 6
  • 60
  • 94
0

Whatever is inside an if statement should evaluate to a boolean, in other words to true or false.

You want to be able to pass arbitrary conditions in String form, then you are gonna have to define a parser for your Strings.

If you really need to do this, which I kinda doubt for the record, consider defining a class that takes a String as constructor argument, two integer values to be evaluated and returns a boolean. Something like:

class Evaluator{
  public Evaluator(String condition){
    // parse condition
  }
  public boolean evaluate(int v1, int v2){ 
    // return true if condition is satisfied, false otherwise
  }
}
posdef
  • 6,498
  • 11
  • 46
  • 94