一 POM
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-jexl3</artifactId> <version>3.2.1</version> </dependency>
二 封装
public class DyMethodUtil { public static Object invokeMethod(String jexlExp, Map<String,Object> map) { JexlEngine jexl = new JexlBuilder().create(); JexlExpression e = jexl.createExpression(jexlExp); JexlContext jc = new MapContext(); for (String key : map.keySet()) { jc.set(key, map.get(key)); } if (null == e.evaluate(jc)) { return ""; } return e.evaluate(jc); } }
三 提供jexl调用的测试方法
public class TestUtil { public String getBooking(String name){ return name+"111"; } }
四 测试
@Autowired SfOrderService sfOrderService; /** * jexl 调用字符串的equals方法 */ @Test public void Test3Jexl() { Map<String,Object> map=new HashMap(); map.put("test","hello"); String expression="test.equals('hello')"; Object obj = DyMethodUtil.invokeMethod(expression,map); System.out.println(obj); String expression1="test.equals('hello111')"; Object obj1 = DyMethodUtil.invokeMethod(expression1,map); System.out.println(obj1); } /** * jexl 调用某个service的方法 */ @Test public void Test4Jexl() throws ScriptException { SfOrder_Req req=new SfOrder_Req(); req.setOrderUUID("2c92808a833aab5501833b048ff10044"); Map<String,Object> map=new HashMap(); map.put("sfOrderService",sfOrderService); map.put("req",req); String expression="sfOrderService.find(req)"; Object obj = DyMethodUtil.invokeMethod(expression,map); System.out.println(obj); } /** * jexl 调用一个方法,并且进行判断 */ @Test public void Test5Jexl(){ TestUtil testUtil=new TestUtil(); String name="hello"; Map<String,Object> map=new HashMap(); map.put("testUtil",testUtil); map.put("name",name); String expression="testUtil.getBooking(name)!=null && testUtil.getBooking(name).length()>5"; Object obj = DyMethodUtil.invokeMethod(expression,map); System.out.println(obj); }
标签:map,String,jexl,Jexl,字符串,new,public,表达式,name From: https://www.cnblogs.com/hanjun0612/p/16776673.html