0

Let´s say that I have the following variable definition:

String strCondition = "x > 0";

Is it possible to apply such a condition using the variable "strCondition"? For example, if I want to use the condition in an "if" statement I would normaly write:

if (x > 0)

But my issue is that the condition can be anything (x > 0, x <= 10, x == -1, etc). If I could do something like:

if (strCondition)

and replace strCondition with its contents to finally process "if (x > 0)"

I hope my question is clear enough. I will appreciate any feedback.

JORGE
  • 167
  • 1
  • 3
  • 12
  • Java doesn't have a native evaluate (for Java code), there is a `ScriptEngine` (e.g. JavaScript, or Jython, or JRuby, etc) with which you can do such things. – Elliott Frisch Feb 14 '16 at 03:45
  • 2
    [The answers to this question will be helpful](http://stackoverflow.com/a/2605050/692410) – Will Richardson Feb 14 '16 at 03:46
  • How complex will the strings be? – Purag Feb 14 '16 at 03:47
  • 2
    I agree with the first two comments, although I do want to add one thing: Always be VERY careful when you write code that will execute the contents of a string that you are not creating some kind of code injection vulnerability. – Ken Clubok Feb 14 '16 at 03:48
  • Which is why I think a valid approach is to accept a fieldname to test and the value to test against - essentially coding your own very simple scripting. This will only work if, as @Purag asked, the tests aren't complex, but eliminates the security complications of executing injected code. – christutty Feb 14 '16 at 03:51
  • If the conditions are always fairly simple and will be formatted appropriately you could parse the statement out yourself. – zgc7009 Feb 14 '16 at 03:57
  • Even **if** you could do this, it would need to do a variable lookup for `x`, which wouldn't be in scope of the evaluation – OneCricketeer Feb 14 '16 at 04:16
  • You could take a look at Groovy, which supports whitelisted sandboxes for scripts. – chrylis -cautiouslyoptimistic- Feb 14 '16 at 04:27
  • This feels like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). I have a hard time imagining an application that would require a limitless number of expressions. Most likely, you can write a class to encapsulate the possible tests. Are all the conditions comparing `x` to a numeric value? – VGR Feb 14 '16 at 05:09

0 Answers0