java - 运行时的动态表达式求值器

标签 java algorithm groovy

我有一个应用程序,我想使用某种表达式计算器对其进行自定义。 我想在不重新编译代码的情况下更改应用程序的某些部分。 我正在考虑使用 groovy 表达式。

例如,我有一个可以通过提供表达式来启用/禁用的功能:

在这种情况下,该功能将被启用

Example 1:
EXPRESSION : status = part-time || status = hourly
INPUT: status = part-time

在这种情况下,该功能将被禁用

Example 2:
EXPRESSION : status = part-time || status = hourly
INPUT: status = permanent

用户需要输入一个表达式和一个输入。表达式应评估为 boolean 表达式

他们也可以改变表达式,程序会通过一些评估来获取它。 顺便说一句,这些表达式已记录在案,并由我向我的应用程序的用户公开

Example 3:
EXPRESSION : salary > 10000
INPUT: salary = 7000

我之前看过一个程序这样做,他们说他们在后台使用了 groovy。 但我无法理解这个概念。

有人可以给我一个想法吗?

最佳答案

使用evaluate 的替代方法。您的变量在绑定(bind)中定义,evaluate 包含表达式:

// setup binding
def emp = [status:'permanent', name:'Hugo']
def binding = new Binding()
binding.status = 'permanent'
binding.status2 = 'part-time'
binding.salary = 7000
binding.employee = emp
println binding.variables

// evaluate the script
def ret = new GroovyShell(binding).evaluate("status == 'part-time' || status == 'hourly'")
println ret

ret = new GroovyShell(binding).evaluate("status2 == 'part-time' || status2 == 'hourly'")
println ret

ret = new GroovyShell(binding).evaluate("salary > 10000")
println ret

ret = new GroovyShell(binding).evaluate("employee.status == 'permanent' || employee.status == 'hourly'")
println ret

返回

[status:permanent, status2:part-time, salary:7000, employee:[status:permanent, name:Hugo]]
false
true
false
true

关于java - 运行时的动态表达式求值器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907695/

相关文章:

c++ - 在流中查找单词序列频率的最佳算法是什么

regex - 在 Groovy 中获取 Mac 地址

java - 指定 groovy-variable 的类型

java - Java 的 Makefile 找不到包

java - 使用 Java 获取 Unix 时间中的日期时间作为大小为 4 字节的字节数组

java - Atmosphere 框架,BroadcasterFactory.getDefault() 替代方案

java - 使单个线程执行完成

c++ - 推力 CUDA 找到每个组(段)的最大值

algorithm - 寻找最大子矩阵算法

grails - IntelliJ IDEA 13.1上的Groovy Grape配置