How to convert string to operator in java

后端 未结 9 1884
情歌与酒
情歌与酒 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条回答
  •  猫巷女王i
    2021-01-16 04:13

    Your approach will never work in Java. Instead you may define your own enum which perform the proper boolean operation like this:

    public static void main(String[] args) {
        boolean result = Operator.parseOperator("==").apply(2, 2);
    }
    
    enum Operator {
    
        LESS("<") {
            @Override public boolean apply(int left, int right) {
                return left < right;
            }
        },
        EQUAL("==") {
            @Override public boolean apply(int left, int right) {
                return left == right;
            }
        };
    
        private final String operator;
    
        private Operator(String operator) {
            this.operator = operator;
        }
    
        public static Operator parseOperator(String operator) {
            for (Operator op : values()) {
                if (op.operator.equals(operator)) return op;
            }
            throw new NoSuchElementException(String.format("Unknown operator [%s]", operator));
        }
    
        public abstract boolean apply(int left, int right);
    }
    

提交回复
热议问题