几种JAVA表达式语言计算工具
测试表达式工具分类
这里测试了几种方式,MS excel,Spring SEPL,MVEL,Google aviator
import com.googlecode.aviator.AviatorEvaluator;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.mvel2.MVEL;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class ExcelTest {
@Test
public void testExcelFormula() throws IOException {
// 加载 Excel 文件
InputStream fis = this.getClass().getResourceAsStream("/formula.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
// 读取公式计算后的值
Cell formulaCell1 = sheet.getRow(1).getCell(1); // 假设公式在第2行第2列
System.out.println("公式计算前的值: " + formulaCell1.getNumericCellValue());
// 修改单元格值
Row row = sheet.getRow(1); // 假设修改第2行
Cell cell = row.getCell(0); // 假设修改第1列
cell.setCellValue(15); // 设置新值
// 重新计算公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == CellType.FORMULA) {
evaluator.evaluateFormulaCell(c); // 重新计算公式
}
}
}
// 读取公式计算后的值
Cell formulaCell = sheet.getRow(1).getCell(1); // 假设公式在第2行第2列
System.out.println("公式计算后的值: " + formulaCell.getNumericCellValue());
// 保存修改后的文件(可选)
FileOutputStream fos = new FileOutputStream("example_updated.xlsx");
workbook.write(fos);
fos.close();
// 关闭资源
fis.close();
workbook.close();
}
@Test
public void testSELFormula() throws IOException {
ExpressionParser parser = new SpelExpressionParser();
// 使用Spring EL计算订单项的总价(虽然这里可以直接调用方法,但为了展示EL,我们依然使用它)
StandardEvaluationContext context = new StandardEvaluationContext();
Map<String, Object> cartItem = new HashMap<>();
cartItem.put("price", new BigDecimal("20.56"));
cartItem.put("quantity", 2);
context.setVariable("cartItem", cartItem);
// BigDecimal totalPrice = parser.parseExpression("#cartItem['price'] = 0; #cartItem['quantity'] = 0; #cartItem['price'] * #cartItem['quantity']")
// .getValue(context, BigDecimal.class);
BigDecimal totalPrice = parser.parseExpression("#cartItem['price'] * #cartItem['quantity']")
.getValue(context, BigDecimal.class);
// 这里只是为了演示EL,实际上可以直接使用orderItem.getTotalPrice()
System.out.println("Order item total price calculated by Spring EL: " + totalPrice);
}
/*
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl3</artifactId>
<version>3.2</version>
*/
@Test
public void testMvELFormula() throws IOException {
Map<String, Object> context = new HashMap<>();
Map<String, Object> cartItem = new HashMap<>();
// cartItem.put("price", new BigDecimal("20.56"));
// cartItem.put("quantity", 2);
context.put("cartItem", cartItem);
// String expression = "cartItem.price=cartItem.price==null?15:cartItem.price; cartItem.quantity=cartItem.quantity==null?1:cartItem.quantity; cartItem.price*cartItem.quantity";
// Corrected expression using bracket notation
String expressions = "cartItem['price'] = cartItem['price'] == null ? new java.math.BigDecimal('15') : cartItem['price']; " +
"cartItem['quantity'] = cartItem['quantity'] == null ? 2 : cartItem['quantity']; " +
"cartItem['price'] * cartItem['quantity']";
Object res = MVEL.eval(expressions, context);
System.out.println(res.getClass());
System.out.println("res: " + res); // 输出: John
}
/*
<groupId>com.googlecode.aviator</groupId>
<artifactId>aviator</artifactId>
<version>5.3.1</version>
*/
@Test
public void testAviator() {
// Create a context with variables
// Map<String, Object> context = new HashMap<>();
// context.put("price", 20.5);
// context.put("quantity", 3);
// Define multiple expressions
// String expressions = "total = price * quantity; discount = total > 50 ? 5 : 0; finalPrice = total - discount; finalPrice";
Map<String, Object> context = new HashMap<>();
Map<String, Object> cartItem = new HashMap<>();
// cartItem.put("price", new BigDecimal("20.56"));
// cartItem.put("quantity", 2);
context.put("cartItem", cartItem);
String expression = "cartItem.price = cartItem.price == nil ? 15 : cartItem.price;" +
"cartItem.quantity = cartItem.quantity == nil ? 2 : cartItem.quantity;" +
"cartItem.price * cartItem.quantity";
Object result = AviatorEvaluator.execute(expression, context);
System.out.println(result.getClass());
// Print the result
System.out.println("Final price: " + result); // Output: Final price: 56.5
}
}
测试结果
使用推荐
推荐使用MVEL,易于java开发理解,功能强大,性能优秀
几种JAVA表达式语言计算工具的更多相关文章
- 四种java代码静态检查工具
[转载]常用 Java 静态代码分析工具的分析与比较 转载自 开源中国社区 http://www.oschina.net/question/129540_23043 1月16日厦门 OSC ...
- Java 高精度浮点数计算工具
说起编程中的高精度数值,我第一反应就是double类型了.的确,double阶码11位,尾数52位,几乎能应对任何苛刻的要求......然而,当我天真地尝试用double来算泰勒展开式的函数值,离散代 ...
- JAVA简单精确计算工具类
1 public class ArithUtil { 2 3 // 默认除法运算精度 4 private static final int DEF_DIV_SCALE = 10; 5 6 privat ...
- java表达式语言mvel2/ognl/spring-expression
<!-- https://mvnrepository.com/artifact/org.mvel/mvel2 --><dependency> <groupId>or ...
- Spring学习总结(四)——表达式语言 Spring Expression Language
SpEL简介与功能特性 Spring表达式语言(简称SpEL)是一个支持查询并在运行时操纵一个对象图的功能强大的表达式语言.SpEL语言的语法类似于统一EL,但提供了更多的功能,最主要的是显式方法调用 ...
- Spring ——表达式语言 Spring Expression Language (转载)
目录 SpEL简介与功能特性 一.为什么需要Spring表达式语言 二.SpEL表达式Hello World! 三.SpEL表达式 3.1.文字表达式 3.2.SPEL语言特性 3.2.1.属性 3. ...
- Java EE之表达式语言EL(上)
1.了解表达式语言 表达式语言(EL)用于在不使用脚本.声明或者表达式的情况下,在JSP页面中渲染数据. EL曾是JSTL 1.0规范(与JSP 1.2)中的一部分,并且只可以用作JSTL标签的特性. ...
- Java Web----EL(表达式语言)详解
Java Web中的EL(表达式语言)详解 表达式语言(Expression Language)简称EL,它是JSP2.0中引入的一个新内容.通过EL可以简化在JSP开发中对对象的引用,从而规范页面 ...
- Java堆栈的应用2----------中缀表达式转为后缀表达式的计算Java实现
1.堆栈-Stack 堆栈(也简称作栈)是一种特殊的线性表,堆栈的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和删除操作,而堆栈只允许在固定一端进行插入和删除 ...
- 应用AXIS开始Web服务之旅(soap web services)——使用三种不同的语言访问创建的Web服务,分别是JAVA、VB、VC
一. 介绍 本文并不是想介绍Web服务的原理.系统架构等,我们假设您已经了解了关于Web服务的一些基本的概念.原理等知识.本文主要是针对那些已经了解Web服务概念,但是还没有亲身体会Web服务所带来令 ...
随机推荐
- linux如何使用ssh进行远程服务
/*********************linux SSH 简单学习********************/ 什么是SSH SSH 为 Secure Shell 的缩写,由 IETF 的网络小组 ...
- hashmap为什么要引入红黑树?
在JDK1.6,JDK1.7中,HashMap采用位桶+链表实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里.但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依 ...
- RocketMQ实战—6.生产优化及运维方案
大纲 1.RocketMQ集群如何进行权限机制的控制 2.如何对RocketMQ集群进行消息堆积的追踪 3.如何处理RocketMQ的百万消息积压问题 4.针对RocketMQ集群崩溃的金融级高可用方 ...
- 洛谷P2789 直线交点数 题解
解题思路 考虑将直线分组,每组内直线互相平行,任意两组直线间交点数量等于两组内直线数量乘积. 分组操作使用dfs,求出交点数量后加入set去重,输出set大小. 时间复杂度O(2NN2)有点鬼畜但是可 ...
- 探秘Transformer系列之(2)---总体架构
探秘Transformer系列之(2)---总体架构 0x00 概述 0.1 流程 使用Transformer来进行文本生成其实就是用模型来预测下一个词,完整流程包括多个阶段,如分词.向量化.计算注意 ...
- vue - [01] 概述
题记部分 001 || 什么是Vue Vue(发音为 /vju:/,类似view)是一款用于构建用户界面的渐进式框架(JavaScript).它基于标准HTML.CSS和JavaScript构建, ...
- CentOS7脚本检测SpringBoot项目JAR包变化后自动重启
#!/bin/bash # 文件目录 fileDir=/usr/local/project/back logDir=/usr/local/project/logs # 设置需要检测的文件路径 file ...
- Java 浮点型去除后面多余的零
当我们输出的小数不知道有几位小数,也不知道后面有没有带零,去掉后面多余零可以采用以下方法.在实际使用中,多用于小数转百分数,百分数前面的小数乘以100后转String输出,输出的String很多带零, ...
- 深入解析 Druid 连接池:连接有效性检测与 Keep-Alive 机制
背景 在 Java 程序中,下面是一个经常会碰到的错误. Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communica ...
- Grafana导入 json 文件的 dashboard 错误 Templating Failed to upgrade legacy queries Datasource xxx not found
前言 编辑或者修改后的 dashboard 保存为 json 文件,在其他环境导入使用,报错 Failed to upgrade legacy queries Datasource xxxxxxx w ...