如何转换 JEXL 表达式的类型?

How to convert type for JEXL expressions?

我使用 JEXL 表达式,因此用户可以在运行时指定表达式,我的应用程序将相应地处理它们。现在作为一种特殊情况,用户想要比较浮点值,但是在 JEXL 上下文中,这些变量包含像“6.8”这样的字符串。 JEXL 引擎抱怨它无法处理字符串和数字。到目前为止一切顺利。

但是在https://commons.apache.org/proper/commons-jexl/reference/syntax.html中我看不到任何类型转换的提示。

有什么方法可以将字符串转换为表达式中的浮点数吗?

所以我找到了一种使用函数命名空间解决此问题的方法(请参阅 https://commons.apache.org/proper/commons-jexl/reference/syntax.html#Functions)。由于这方面的文档似乎很少,所以我发布了解决方案。

使用通过命名空间添加的附加功能创建 JexlEngine。

    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();

有了这个,您将能够处理像

这样的表达式
float:parseFloat("10") > 8

因此现在可以在公式中进行类型转换。