0

Possible Duplicate:
Is there a java equivalent of the python eval function?

There is a String, something like String str = "if a[0]=1 & a[1]=2". How to use this string in a real IF THEN expression? E.g.:

for (Integer[] a : myNumbers) {
   if a[0]=1 & a[1]=2 {  // Here I'd like to use the expression from str
      //...
   }
}
Community
  • 1
  • 1
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • 2
    It's just impossible. You would have to implement an expression evaluator and feed it with the array, because the evaluator wouldn't have access to local variables. You're probably trying to solve a problem using a too complex or inappropriate solution. What is the higher-level problem you're trying to solve? – JB Nizet Jan 04 '12 at 20:55
  • Yeah, that only works in dynamic languages, like JavaScript. – Mitch Jan 04 '12 at 20:58
  • You can write your own interpreter, but you can't 'feed' the string data into the if keyword – Amir Afghani Jan 04 '12 at 20:59
  • 2
    Just because the answer is "it can't be done" doesn't mean that the question should be downvoted so quickly. – Wayne Jan 04 '12 at 21:00
  • And I'd recommend using the short-circuit and (`&&`) instead, regardless. – Clockwork-Muse Jan 04 '12 at 21:03
  • 1
    It can be done - it just wouldn't be advisable. See my answer below if you want more information. The motives behind the question here are more important than the answer in this case, I believe. – Dan Hardiker Jan 04 '12 at 21:06

2 Answers2

4

Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java.

There are two common ways you can approach this, listed below. However they have a significant performance impact when it comes to the runtime of your application.


Script Execution

You could fire up a ScriptEngine, build a ScriptContext, execute the fragment in Javascript or some other language, and then read the result of the evaluation.


Parsing

You could build a lexical parser that analyses the string and converts that into the operations you want to perform. In Java I would recommend you look at JFlex.

Dan Hardiker
  • 3,013
  • 16
  • 19
0

I don't think you can do what you're asking.

Also your java doesn't seem to make much sense. Something like this would make more sense:

for (Integer a : myNumbers) {
   if (a.equals(Integer.valueOf(1))){
      //...
   }
}

You can however say:

if("hello".equals("world")){
    //...
}

And you can build a string:

String str = "if "+a[0]+"=1 & "+a[1]+"=2"

And you can put that together and say:

String str = "if "+a[0]+"=1 & "+a[1]+"=2"
if(str.equals("if 1=1 & 2=2")){
    //...
}

But I think you're probably just trying to do something the wrong way

Edd
  • 8,402
  • 14
  • 47
  • 73