jexl2 执行字符串Java代码
一,引入jar包,
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jexl -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl</artifactId>
<version>2.1.1</version>
</dependency>
二:案例:
// JexlContext jc = new MapContext(); jc.set("a", 1); jc.set("b", "0"); jc.set("ans", new StringBuffer()); Expression e = new JexlEngine().createExpression("while (a < 10) {a = a + 1; ans.append(a);}"); e.evaluate(jc); System.out.println(jc.get("ans")); Expression expr; JexlContext ctxt = new MapContext(); JexlEngine jexl = new JexlEngine(); // 表达式 String exps = "if(c1>c2) {c3=0}"; expr = jexl.createExpression(exps); // case 1 ctxt.set("c1", 1); ctxt.set("c2", 2); expr.evaluate(ctxt); System.out.println((Integer) ctxt.get("c3") == (Integer) (0)); // case 2 ctxt.set("c1", 2); ctxt.set("c2", 1); expr.evaluate(ctxt); System.out.println((Integer) ctxt.get("c3") == (Integer) (0));
MapContext 传入和取得变量。