貌似有这么几种开源引擎:Ognl/MVEL/Aviator/JSEL
大概看了看,选了MVEL
代码在此: https://github.com/mvel/mvel
支持的表达式在此: https://en.wikisource.org/wiki/MVEL_Language_Guide https://en.wikibooks.org/wiki/Transwiki:MVEL_Language_Guide 很NB啊,还支持循环等语法
Maven里这么引用:
<!-- https://mvnrepository.com/artifact/org.mvel/mvel2 --> <dependency> <groupId>org.mvel</groupId> <artifactId>mvel2</artifactId> <version>2.4.14.Final</version> </dependency>
大概这么调用:
package com.why;
import java.util.HashMap; import java.util.Map;
import org.mvel2.MVEL;
public class TestMvel {
public static void main(String[] args) { String ex1 = "(a+b*3-c/200+d*2)"; String ex2 = ex1+">0";
Map vars = new HashMap(); vars.put("a", new Integer(100)); vars.put("b", new Integer(200)); vars.put("c", new Integer(40000)); vars.put("d", new Integer(200));
Double result1 = (Double) MVEL.eval(ex1, vars); Boolean result2 = (Boolean) MVEL.eval(ex2, vars); System.out.println(result1.intValue()); System.out.println(result2.booleanValue()); String ex3="if (x > 0) {\r\n" + " System.out.println(\"Greater than zero!\");\r\n" + "}\r\n" + "else if (x == -1) { \r\n" + " System.out.println(\"Minus one!\");\r\n" + "}\r\n" + "else { \r\n" + " System.out.println(\"Something else!\");\r\n" + "}"; vars = new HashMap(); vars.put("x", new Integer(2)); MVEL.eval(ex3, vars); vars.put("x", new Integer(-1)); MVEL.eval(ex3, vars); String ex4="def hello() { java.lang.Process p = java.lang.Runtime.getRuntime().exec(new String[] { \"cmd\", \"/c\", \"dir\" });" + "java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream(),\"GBK\"));" + "String line = null;\r\n" + " while ((line = input.readLine()) != null) {\r\n" + " System.out.println(line);\r\n" + " }" + "input.close();\r\n" + " }hello();"; MVEL.eval(ex4,vars); }
}
|