How to convert string to operator in java

后端 未结 9 1661
情歌与酒
情歌与酒 2021-01-16 03:12

I want to convert some String to an operator like this:

int value = 1;
int valueToCompare = 3;
String operation = \"<\";

if (value operation         


        
9条回答
  •  孤街浪徒
    2021-01-16 03:49

    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.

提交回复
热议问题