How to convert string to operator in java

后端 未结 9 1885
情歌与酒
情歌与酒 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 04:08

    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 opMap = new HashMap();
            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
        }
    }
    

提交回复
热议问题