-1

I have a String for example:

String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";

where resultSet is a map.

Is there a way I can convert it to expression so that I can evaluate its value.

Say:

int i=  (resultSet.get("PRIMARY_ROLE")=='COO Business Management Team' && resultSet.get("DEPT_LEVEL")=='5') ? 1:0 ;
achAmháin
  • 4,176
  • 4
  • 17
  • 40
Suvriti Gandhi
  • 185
  • 1
  • 2
  • 10
  • write a parser. Or write it to a file with enough surroundings to make it a syntactically correct class definition, then compile, load and execute it. Since you didn't know this string as you wrote your code, it must come from an external source. Executing such code is always dangerous. – Ronald Dec 06 '17 at 10:33
  • What is the source of this code string? It might be easier extracting the pieces you need than trying to parse what you have now. – Tim Biegeleisen Dec 06 '17 at 10:36
  • Use an existing parser, for example this one: https://github.com/stefanhaustein/expressionparser (disclaimer: I am biased because I wrote it) – Stefan Haustein Dec 06 '17 at 10:36

1 Answers1

0

If each of expressions is a syntactically correct JavaScript then you can use Oracle Nashorn engine shipped as part of JDK starting from Java 8 (previously it was Mozilla Rhino):

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByExtension("js");

    String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";
    Bindings bindings = se.createBindings();
    bindings.put("resultSet",
            new HashMap<String, String>() {{
                put("PRIMARY_ROLE","COO Business Management Team");
                put("DEPT_LEVEL","5");
            }});

    Object result = se.eval(s, bindings);
    System.out.println("Expression evaluates to "+ result);
}
yegodm
  • 1,014
  • 7
  • 15