elspring-elmvelfree-variablejuel

List free variables in an EL expression


I have an application which contains some EL evaluation used for programmatic configuration. Given an EL expression I want to get what free variables it contains without actually evaluating it. The intention is to provide a UI where end users can bind values to free variables before pressing an "evaluate" button.

Unfortunately javax.el.ValueExpression does not provide this functionality, so I may need to use vendor-specific API. It is quite early in the development, so I have not yet fixed my choice of implementation. I have thought of MVEL, JUEL and SpEL, but of course whatever I chose should have the functionality I described above.


Solution

  • MVEL's ParserContext can tell you all about the variables organized by locals and inputs.

    ParserContext ctx = ParserContext.create();
    MVEL.analysisCompile("a = 0; b = 0;", ctx);
    
    HashMap<String, Class> vars = ctx.getVariables();
    
    assert vars.containsKey("a") && Number.class.isAssignableFrom(vars.get("a"));
    assert vars.containsKey("b") && Number.class.isAssignableFrom(vars.get("b"));