How to convert string to operator in java

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

    The simplest way would be a chain of if-else statements checking what the the operator is and then performing the mathematical expression.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-16 04:14

    You can use ScriptEngine for that, works for any other JavaScript expressions also :

    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    
    
    int value = 1;
    int valueToCompare = 3;
    String operation = "<";
    
    if ((Boolean)engine.eval("" + value + operation + valueToCompare)) {
        System.out.println("Here we are.");  
    }
    
    0 讨论(0)
提交回复
热议问题