How to convert string to operator in java

后端 未结 9 1669
情歌与酒
情歌与酒 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: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.");  
    }
    

提交回复
热议问题