Ben Hoffman
Ben Hoffman

Reputation: 147

Java - generating conditions from string

I'm trying to generate some conditions using string i get as input.
For example, i get as in put the string "length = 15" and i want to create from that the condition: length == 15. To be more specific, i have an int in my program called length and it is set to a specific value.
i want to get from the user a conditon as input ("length < 15" or "length = 15"....) and create an if statement that generates the condition and test it.
What is the best way of doing that?
Thanks a lot
Ben

Upvotes: 0

Views: 425

Answers (3)

Sbodd
Sbodd

Reputation: 11454

Depending on what restrictions you can place on your input format, you could consider using Rhino to embed Javascript. Your 'conditions' then just have to be valid JavaScript code. Something like this (disclaimer: haven't compiled it):

import javax.script.*;

public bool evalCondition (Object context, String javascript)  {
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
  Object result = engine.eval(javascript);
  Boolean condTrue = (Boolean)result;
  return condTrue;
}

See the Embedding Rhino Tutorial for more details.

Upvotes: 0

aioobe
aioobe

Reputation: 421100

Unless you're talking about code-generation (i.e. generating Java-code by input strings) you can't generate an if-statement based on a string.

You'll have to write a parser for your condition-language, and interpret the resulting parse trees.

In the end it would look something like this:

Condition cond = ConditionParser.parse("length = 15");

if (cond.eval()) {
    // condition is true
}

Upvotes: 1

loveToCode
loveToCode

Reputation: 139

Use a string tokenizer. The default method to distinguish between tokens (or the smallest parts of the input string) is white space, which is to your benefit. check out javadocs for details: http://docs.oracle.com/javase/1.3/docs/api/java/util/StringTokenizer.html

Upvotes: 0

Related Questions