4
private String boundaries = "(x > 750) & (x < 900)";
if (boundaries) {
//Do stuff
}

I wanted to be able to use the string as the variable in the if clause, and then change the string independently without having to edit the code itself. The example idea doesn't work, I was wondering if there is a mistake in it or another way to do this without using strings.

Thank you.

Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80
user3144201
  • 171
  • 1
  • 9

2 Answers2

8

Java is not a dynamically compiled language, so if you want to evaaluate such an expression you can use Javascript from Java.

Try this code:

      String boundaries = "(x > 750) & (x < 900)";
      ScriptEngineManager manager = new ScriptEngineManager();
      ScriptEngine engine = manager.getEngineByName("javascript");

      engine.eval("var x = 810;"); // Define x here
      engine.eval("var bln = false;")
      engine.eval("if (" + boundaries + ") bln = true; ")
      if((boolean)engine.eval(bln)) {
          // Do stuff
      }

Hope this helps. Reference: Oracle: Java Scripting Programmer's Guide

Gergely Králik
  • 440
  • 4
  • 14
0

Java is not a dynamically compiled language in this sense.

What you can do is use beanshell for compilation of code at runtime, or use the JavaScript framework to implement the expression.

In Java, the simplest option is to do this

int min = Integer.parseInt(minAsString);
int max = Integer.parseInt(maxAsString);
if (x > min && x < max) {
   // do stuff
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130