I want to convert some String
to an operator like this:
int value = 1;
int valueToCompare = 3;
String operation = \"<\";
if (value operation
Sounds like you need a switch based around a string (for Java 7 and above - otherwise simple use if
/else
), and a set of Comparator objects e.g.
switch (operation) {
case ">" : return new GreaterThanComparator();
or
if (operation.equals(">")) {
return new GreaterThanComparator();
}
where GreaterThanComparator
implements the Comparator
interface. The class you've created implements your comparison functionality and could do a lot more besides. It's the closest Java has to the encapsulation of a function.
Note that the Comparator
above can be used directly in Java collections in order to perform sorting etc.
You could use lookup tables (e.g. a Map
of String
/Comparators
) or similar if you have a lot of these comparisons to make. I think the important part of the above is the encapsulation of the behaviour via the Comparator
object.
An alternative is to use the scripting engine built into Java and parse (say) Javascript statements. That's perhaps more work, but certainly a more extensible solution. Note that you're not limited to Javascript, and a number of scripting languages exist, including Beanshell, Jython etc.
Answer
For completeness¸I would like to add that there already exists a lot of code for this. I know you asked a very specific question, but the general answer would be to look at existing solutions how that is done.
Example:
Built-in method for evaluating math expressions in Java
Create a custom method which does it for you..
Something like this
private static boolean parseExpression(int number1, String operator, int number2)
{
if ("<".equals(operator)) {
return number1 < number2;
} else if (">".equals(operator)) {
return number1 > number2;
} else if ("<=".equals(operator)) {
return number1 <= number2;
} else if (">=".equals(operator)) {
return number1 >= number2;
} else if ("==".equals(operator)) {
return number1 == number2;
} else {
throw new IllegalArgumentException("Invalid operator");
}
}
private static boolean parseExpression(double number1, String operator, double number2)
{
if ("<".equals(operator)) {
return Double.compare(number1, number2) == -1;
} else if (">".equals(operator)) {
return Double.compare(number1, number2) == 1;
} else if ("<=".equals(operator)) {
return Double.compare(number1, number2) <= 0;
} else if (">=".equals(operator)) {
return Double.compare(number1, number2) >= 0;
} else if ("==".equals(operator)) {
return Double.compare(number1, number2) == 0;
} else if ("!=".equals(operator)) {
return Double.compare(number1, number2) != 0;
} else {
throw new IllegalArgumentException("Invalid operator");
}
}
If you don't want to use a comparator, it's something "simple" but should work. For double/floats should do a bit more of work anyway
P.S with Enums you could do something very elegant. With Java7 you can use switch-strings
too.
It is not directly possible, you'll have to write some code. One possibility is using enums:
enum Operation {
LESS_THAN("<") {
@Override int compare(int o1, int o2) {
return o1 - o2;
}
},
...;
private final String operator;
private Operation(final String operator) {
this.operator = operator;
}
private static final Map<Operation, String> MAP = new HashedMap<Operation, String>();
static {
for (final Operation op: values()) MAP.put(op.operator, op);
}
public static Operation valueOf(final String op) {
return MAP.get(op);
}
}
Usage example:
int cmp = Operation.valueOf(operation).compare(value, valueToCompare);
You could try using a switch statement:
switch(operation) {
case "<" : //code here
break;
case ">" : //code here
break;
case "==" : //code here
break;
}
you may try this:
import java.util.*;
interface Operator {
boolean compare(int a, int b);
}
class Launch
{
public static void main (String[] args) throws java.lang.Exception
{
Map<String, Operator> opMap = new HashMap<String, Operator>();
opMap.put(">", new Operator() {
@Override public boolean compare(int a, int b) {
return a > b;
}
});
opMap.put("<", new Operator() {
@Override public boolean compare(int a, int b) {
return a < b;
}
});
opMap.put("==", new Operator() {
@Override public boolean compare(int a, int b) {
return a == b;
}
});
String op = ">";
int i = 4, j = 5;
boolean test = opMap.get(op).compare(i, j);
System.out.printf("test: %b, i: %d, op: %s, j: %d\n", test, i, op, j);
//prints: test: false, i: 4, op: >, j: 5
}
}