javatype-conversionjexl

How to convert type for JEXL expressions?


I use JEXL expressions so users can specify expressions at runtime and my application will process them accordingly. Now as a special case users want to compare floating point values, however in the JEXL context these variables contain strings like "6.8". The JEXL engine complains that it cannot process strings and numbers. So far so good.

However in https://commons.apache.org/proper/commons-jexl/reference/syntax.html I can nowhere see any hint of type conversion.

Is there any way of converting a string to float inside the expression?


Solution

  • So I found a way to resolve this using function namespaces (see https://commons.apache.org/proper/commons-jexl/reference/syntax.html#Functions). As it seems documentation on this is scarce I am posting the solution.

    Create the JexlEngine with additional functions added via namespaces.

        Map<String, Object> namespace = new TreeMap<>();
        namespace.put("float", Float.class);
            
        JexlBuilder builder = new JexlBuilder();
        builder.silent(false);
        builder.strict(true);
        builder.namespaces(namespace);
        JexlEngine engine = builder.create();
    

    With this you will be able to process expressions like

    float:parseFloat("10") > 8
    

    so the type conversion is now possible within the formula.