How to convert string to operator in java

后端 未结 9 1654
情歌与酒
情歌与酒 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:56

    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 MAP = new HashedMap();
        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);
    

提交回复
热议问题