750) & (x < 900)"; if (boundaries) { //Do stuff } I...">

Using a string as a variable clause in an if statement

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

I wanted to be able to use a string as a variable in an if clause, and then change the string independently without editing the code itself. The sample idea does not work, I was wondering if there was an error in it or some other way to do this without using strings.

Thanks.

+4
source share
2 answers

Java is not a dynamically compiled language, so if you want to evaluate this 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. Link: Oracle: Java Scripting Programmer's Guide

+8
source

Java .

, beanshell JavaScript .

Java -

int min = Integer.parseInt(minAsString);
int max = Integer.parseInt(maxAsString);
if (x > min && x < max) {
   // do stuff
}
0

Source: https://habr.com/ru/post/1523771/


All Articles