ExpressionUtil
Introduction
Similar to template engines, Hutool encapsulates popular expression evaluation engines as a facade pattern, providing a unified API to eliminate differences. The existing engine implementations include:
Usage
First, introduce the template engine we need. After the introduction, Hutool can automatically identify and use it through the SPI mechanism. Let’s take Aviator
as an example:
<dependency>
<groupId>com.googlecode.aviator</groupId>
<artifactId>aviator</artifactId>
<version>5.2.7</version>
</dependency>
Executing Expressions
final Dict dict = Dict.create()
.set("a", 100.3)
.set("b", 45)
.set("c", -199.100);
// -143.8
final Object eval = ExpressionUtil.eval("a-(b-c)", dict);
Custom Engine Execution
If multiple engines are introduced in the project and we want to choose a specific engine to execute, we can do:
ExpressionEngine engine = new JexlEngine();
final Dict dict = Dict.create()
.set("a", 100.3)
.set("b", 45)
.set("c", -199.100);
// -143.8
final Object eval = engine.eval("a-(b-c)", dict);
Creating a Custom Engine
The core of the engine is to implement the ExpressionEngine
interface, which has only one method: eval
. After implementing this interface, create a spi file cn.hutool.extra.expression.ExpressionEngine
in the META-INF/services/
directory of the project:
com.yourProject.XXXXEngine
This way, you can directly call ExpressionUtil.eval
to execute the expression.