MVEL2.0的使用實例(一)


本文是對java整合mvel2.0的一點示例:

如果表達式中有變量,解析表達式時必須傳一個map

MVEL.eval(expression, vars);
/**
* 基本解析表達式
*/
@Test
public void test(){
String expression ="foobar > 99";
Map vars = new HashMap();
vars.put("foobar",new Integer(100));
// We know this expressionshould return a boolean.
Boolean result = (Boolean) MVEL.eval(expression, vars);
if (result.booleanValue()) {
System.out.println("Itworks!");
}
}

/**
* 變量判空
*/
@Test
public void test4(){
String expression = "a == empty && b == empty";

Map<String, Object> paramMap = new HashMap<>();
paramMap.put("a", "");
paramMap.put("b", null);
Object object = MVEL.eval(expression, paramMap);
System.out.println(object); // true
}

   /**
*
*/
@Test
public void test(){
HashMap<Object, Object> srcMap = new HashMap<>();
srcMap.put("name","zs");
srcMap.put("age",10);
srcMap.put("sex","女");
//字段映射關系
HashMap<String, String> mapping = new HashMap<>();
mapping.put("name","name");
mapping.put("age","age");
//這里先把當前年份寫死為2019
mapping.put("birthYear","2019-age");
//目標對象
HashMap<Object, Object> targetMap = new HashMap<>();
//k為目標表字段,v為轉換規則
mapping.forEach((k,v)->{
Object reValue = MVEL.eval(v,srcMap);
System.out.println(v+":"+reValue);
targetMap.put(k,reValue);
});
System.out.println("源對象"+srcMap); //源對象{sex=女, name=zs, age=10}
System.out.println("目標對象"+targetMap); //目標對象{birthYear=2009, name=zs, age=10}
}
/**
* 獲取對象屬性
*/
@Test
public void test2(){
UserInfo user = new UserInfo();
user.setUserName("1234");
String expression = "user.userName = '123'";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("user",user);
Object object = MVEL.eval(expression, paramMap);
System.out.println(object); // true
}
 /**
* 多語句分號隔開 返回值無需 return
*/
@Test
public void test3(){
String expression = " a = 10; b = (a = a * 2) + 10;b;";

  Map<String, Object> paramMap = new HashMap<>();
//即便map沒有任何內容 ,也需要傳map 不然會報錯
        Object object = MVEL.eval(expression,paramMap );
        System.out.println(object); // true
}[
/**
* null 和nil 都表示空
*/
@Test
public void test4(){
String expression = "a == null && b == nil";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("a", null);
paramMap.put("b", null);
Object object = MVEL.eval(expression, paramMap);
System.out.println(object); // true
}
/**
* 兩種解析表達式方式
*/
@Test
public void test5(){
UserInfo foo = new UserInfo();
foo.setUserName("test");
Map context = new HashMap();
String expression = "foo.userName == 'test'";
VariableResolverFactory functionFactory = new MapVariableResolverFactory(context);
context.put("foo",foo);
Boolean result = (Boolean) MVEL.eval(expression,functionFactory);
System.out.println(result);

Serializable compileExpression = MVEL.compileExpression(expression);
result = (Boolean) MVEL.executeExpression(compileExpression, context, functionFactory);
System.out.print(result);
}
/**
*基本表達式計算,map工廠
*/
@Test
public void test3(){
UserInfo userInfo = new UserInfo();
String exp = "a + b > c";
Map varsMap = new HashMap();
varsMap.put("a", 1); varsMap.put("b", 2);varsMap.put("c", 2);
VariableResolverFactory factory = new MapVariableResolverFactory(varsMap);
Object eval = MVEL.eval(exp, factory);
System.out.println(eval);
}

/**
*空安全運算符user.?parent.name
*/
@Test
public void test4(){
UserInfo user = new UserInfo();
user.setUserName("xm");
user.setPassword("123");
user.setParent(new Parent("xmfather"));
//user 有一個parent對象屬性 parent屬性中有一個name屬性
String exp = "user.?parent.name";
Map<String,Object> factory = new HashMap<>();
factory.put("user",user);
// VariableResolverFactory factory = new MapVariableResolverFactory();
Object eval = MVEL.eval(exp, factory);
System.out.println(eval);
}

/**
* 集合遍歷
*/
@Test
public void test5(){
List<Integer> list = new ArrayList<>();
Map<String,Object> map = new HashMap<>();
Map<String,Object> map2 = new HashMap<>();
list.add(0);
list.add(1);
list.add(2);
String exp = "list[0]";
String exp2 = "map2.list";
map2.put("list",list);
map.put("list",list);
map.put("map2",map2);
Object eval = MVEL.eval(exp2,map);
System.out.println(eval);
}
/**
* Strings as Arrays
*/
@Test
public void test6(){
String foo = "My String";
String exp = "foo[0]";
Map<String,Object> map = new HashMap<>();
map.put("foo",foo);
Object eval = MVEL.eval(exp,map);
System.out.println(eval);
}

/**
* If-Then-Else
*/
@Test
public void test7(){
String exp = "\n" +
"if (a > 0) {\n" +
" System.out.println(\"Greater than zero!\");\n" +
"}\n" +
"else if (a == -1) { \n" +
" System.out.println(\"Minus one!\");\n" +
"}\n" +
"else { \n" +
" System.out.println(\"Something else!\");\n" +
"}\n";
Map<String,Object> map = new HashMap<>();
map.put("a",1);
Object eval = MVEL.eval(exp,map);
}  
/**
* 三元聲明
*/
@Test
public void test9(){
String expression = "num > 0 ? \"Yes\" : \"No\";";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("num", 2);
Object object = MVEL.eval(expression, paramMap);
System.out.println(object);
}
/**
* Foreach 它接受由冒號分隔的兩個參數,第一個是當前元素的局部變量,
* 第二個是要迭代的集合或數組。
*/
@Test
public void test10(){

List<String> people = new ArrayList<>();
people.add("name");
people.add("xm");
people.add("xl");
String expression = "count = 0;\n" +
"foreach (name : people) {\n" +
" count++;\n" +
" System.out.println(\"Person #\" + count + \":\" + name);\n" +
"}";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("people", people);
Object object = MVEL.eval(expression, paramMap);
System.out.println(object);

String exp2 = "str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n" +
" \n" +
"foreach (el : str) {\n" +
" System.out.print(\"[\"+ el + \"]\"); \n" +
"}";
MVEL.eval(exp2,paramMap);



}

/**
* MVEL 2.0,使用for關鍵字簡單地簡化foreach
*/
@Test
public void test10_2(){
String expression ="['Jim','Bob','Tom']";
List<String> l =(List<String>) MVEL.eval(expression);
for(String str:l){
System.out.println(str);
}

String exp = "count = 0;\n" +
"for (name : l) {\n" +
" count++;\n" +
" System.out.println(\"l #\" + count + \":\" + name);\n" +
"}";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("l",l);
MVEL.eval(exp,paramMap);
}
  /**
*MVEL對列表、數組、map的操作
*/
@Test
public void test11(){
//list
String expression ="['Jim','Bob','Tom']";
List<String> l =(List<String>) MVEL.eval(expression);
for(String str:l){
System.out.println("list"+str);
}

//數組
String exp2 = "{'Jim','Bob','Tom'}";
Object str = MVEL.eval(exp2);
if(str.getClass().isArray()){
System.out.println("array"+String.valueOf(Array.get(str, 0)));
}

//map
String exp3 ="['Bob' : new com.demo.po.UserInfo('Bob'), 'Michael' : new com.demo.po.UserInfo('Michael')]";
Map o = (Map ) MVEL.eval(exp3);
UserInfo u = (UserInfo) o.get("Bob");
System.out.println("map"+u.getUserName());

}

/**
* Do While
*/
@Test
public void test12(){
String exp3 = "do { \n" +
" System.out.println(\"當符合while中條件就執行:\"+x);\n" +
" --x } \n" +
"while (x >= 5 );";
Map<String,Object> map = new HashMap<>();
map.put("x",10);
MVEL.eval(exp3,map);

}
/**
* Do Until
*/
@Test
public void test13(){
String exp3 = "do { \n" +
" System.out.println(\"當不符合while中條件就執行:\"+x);\n" +
" --x } \n" +
"until (x < 5 );";
Map<String,Object> map = new HashMap<>();
map.put("x",10);
MVEL.eval(exp3,map);}

}
/**
* while
*/
@Test
public void test(){
String exp3 = "while(x >= 5){" +
"System.out.println(\"當符合while中條件就執行:\"+x);" +
"--x}";
Map<String,Object> map = new HashMap<>();
map.put("x",10);
MVEL.eval(exp3,map);
}


/**
* until
*/
@Test
public void test2(){
String exp3 = "until(x < 5){" +
"System.out.println(\"當不符合while中條件就執行:\"+x);" +
"--x}";
Map<String,Object> map = new HashMap<>();
map.put("x",10);
MVEL.eval(exp3,map);
}
/**
* 投影1.0
*/
@Test
public void test3(){
List<UserInfo> users = new ArrayList<>();
users.add(new UserInfo("xm"));
users.add(new UserInfo("xh"));
users.add(new UserInfo("xl"));
String exp3 = "parentNames = (userName in users); parentNames;" ;
Map<String,Object> map = new HashMap<>();
map.put("users",users);
List<UserInfo> eval = (List<UserInfo>) MVEL.eval(exp3, map);
System.out.println(eval);
}
/**
*投影2.0
*/
@Test
public void test3_2(){
List<UserInfo> users = new ArrayList<>();
users.add(new UserInfo(new Parent("xm")));
users.add(new UserInfo(new Parent("xh")));
users.add(new UserInfo(new Parent("xl")));
// String exp3 = "foo=(name in (parent in users));foo" ;
String exp3 = "foo=(parent.name in users);foo" ;
Map<String,Object> map = new HashMap<>();
map.put("users",users);
List<UserInfo> eval = (List<UserInfo>) MVEL.eval(exp3, map);
System.out.println(eval);
}

/**
*投影3.0過濾投影
*/
@Test
public void test3_3(){
List<UserInfo> users = new ArrayList<>();
List<UserInfo> fams = new ArrayList<>();
users.add(new UserInfo("xm",fams));
users.add(new UserInfo("xh",fams));
users.add(new UserInfo("xl",fams));
String exp3 = "($ in users if $.userName contains 'h');" ;
Map<String,Object> map = new HashMap<>();
map.put("users",users);
Object eval = MVEL.eval(exp3, map);
System.out.println(eval);
}
/**
* 過濾投影2.0
*/
@Test
public void test4(){
String exp3 = "(($ < 10) in [2,4,8,16,32]); " ;
String exp4 = "($ in [2,4,8,16,32] if $ < 10); "; // returns [2,4,8]
Object eval = MVEL.eval(exp3);
System.out.println(eval);
Object eval2 = MVEL.eval(exp4);
System.out.println(eval2);
}
/**
* 導入調用簡單hello函數
*/
@Test
public void test()throws IOException {
File scriptFile = new File("src/main/resources/mvel/hello.el");
Map map = new HashMap();
map.put("name", "小明");
MVEL. evalFile(scriptFile, ParserContext.create(), map);
Object obj = MVEL. eval("hello(name);", map);
}

//hello.el的內容
def hello(String name){
System.out.println("hello" + name);
}
/**
* Lambda(匿名函數)
*/
@Test
public void test2(){
String exp = "threshold = def (x) { x >= 10 ? x : 0 };\n" +
"result = threshold(num);\n" +
"System.out.println(result);";
Map map = new HashMap();
map.put("num",15);
MVEL. eval(exp,map);
}


目前攔截器,閉包,交集,類型轉換以及使用格式還有些問題沒研究透



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM