1. 前言
在上一篇文章中,我們簡單介紹了一下表達式引擎,并引出我們的主角QLExpress.在這篇文章中,我們先來一個QLExpress的熱身。
2. 初探QLExpress
源碼地址:https://github.com/alibaba/qlExpress
筆者下載源碼的版本是3.3.1-SNAPSHOT快照版。下載源碼后,代碼結構如下圖所示
大家在學習的時候,主要關注test包下的測試案例即可。
3. helloword程序
首選我們在test包下創建自己學習的包名,筆者建立的是self包,self包下創建helloworld包。如圖所示:
代碼如下:
/*** 類描述: 入門程序 helloworld* @author admin* @version 1.0.0* @date 2023/11/13 13:02*/ public class HelloWorld {@Testpublic void test() throws Exception{ExpressRunner runner = new ExpressRunner();DefaultContext<String, Object> context = new DefaultContext<String, Object>();context.put("a",1);context.put("b",2);context.put("c",3);String express = "a+b*c";Object r = runner.execute(express, context, null, true, false);System.out.println(r);} }
代碼說明:相信有程序基礎的小伙伴,這段代碼應該難不住大家。
ExpressRunner:
語法分析和計算的入口類
DefaultContext:
表達式計算的數據注入接口,作者程序中默認的實現類
execute:執行方法,代碼如下
/*** 執行一段文本** @param expressString 程序文本* @param context 執行上下文* @param errorList 輸出的錯誤信息List* @param isCache 是否使用Cache中的指令集* @param isTrace 是否輸出詳細的執行指令信息* @return* @throws Exception*/ public Object execute(String expressString, IExpressContext<String, Object> context, List<String> errorList,boolean isCache, boolean isTrace) throws Exception {return this.execute(expressString, context, errorList, isCache, isTrace, null); }
代碼的運行結果: