在Mvel中可以使用List和Map,在测试的时候做个记录
准备工作
开发Mvel函数脚本加载器,用于读取MVEL脚本
package file;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* @Description
* @Authror taren
* @DATE 2019/8/28 10:43
*/
public class MvelFileLoader {
public static String load() {
//该脚本文件存在于resources目录下的mvel目录中
URL url = MvelFileLoader.class.getClassLoader().getResource("mvel/test01.mvel");
StringBuilder sb = new StringBuilder();
if (url != null) {
try {
String builtInExpr = IOUtils.toString(url, StandardCharsets.UTF_8);
sb.append(builtInExpr);
sb.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
开发一个简单的实体装载类Person
package approve.entity;
/**
* @Description
* @Authror taren
* @DATE 2019/8/27 18:02
*/
public class Person {
private String name;
private Integer date1;
private Integer date2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDate1() {
return date1;
}
public void setDate1(Integer date1) {
this.date1 = date1;
}
public Integer getDate2() {
return date2;
}
public void setDate2(Integer date2) {
this.date2 = date2;
}
public Person() {
}
public Person(String name, Integer date1, Integer date2) {
this.name = name;
this.date1 = date1;
this.date2 = date2;
}
}
编写使用List的脚本
简单的描述一下逻辑:统计date相减大于30的人数
import approve.entity.Person;
import java.util.*;
all=0;
aList=[];
def count(list){
for(item:list){
if(sub(item.date1,item.date2)){
++all;
aList.add(item.name);
}
}
return aList.size();
}
def sub(a,b){
return Math.subtractExact(a,b)>30;
}
编写测试类
package file;
import approve.entity.Person;
import org.mvel2.MVEL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description
* @Authror taren
* @DATE 2019/8/28 14:41
*/
public class MvelTest02 {
public static void main(String[] args) {
Person person1 = new Person("tt", 31, 0);
Person person2 = new Person("tx", 31, 0);
Person person3 = new Person("t5", 34, 2);
Person person4 = new Person("t6", 34, 1);
List people = new ArrayList<>();
people.add(person1);
people.add(person2);
people.add(person3);
people.add(person4);
Map context = new HashMap<>();
context.put("list", people);
String express = "count(list)";
System.out.println("result =" + MVEL.eval(MvelFileLoader.load() + express, context));
}
}
输出
//测试List
result =4
编写使用Map的脚本
需求:满足相减大于30的人去重的数量
import approve.entity.Person;
import java.util.*;
all=0;
aMap=[:];
def count(list){
for(item:list){
if(sub(item.date1,item.date2)){
++all;
aMap.put(item.name,item.name);
}
}
return aMap.keySet().size();
}
def sub(a,b){
return Math.subtractExact(a,b)>30;
}
测试输出
修改一下测试数据
Person person1 = new Person("tt", 31, 0);
Person person2 = new Person("tx", 31, 0);
Person person3 = new Person("t5", 34, 2);
Person person4 = new Person("t5", 34, 1);
//测试Map
result =3
写在后面
Mvel表达式编译和不编译性能差距极大,在使用的时候最好先编译,然后使用