Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a string as a variable clause in an if statement [duplicate]

Tags:

java

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.

like image 204
user3144201 Avatar asked Feb 14 '23 23:02

user3144201


1 Answers

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

like image 75
Gergely Králik Avatar answered May 16 '23 02:05

Gergely Králik