java将字符串转换成可执行代码(commons-jexl功能简介)

参考自:

        1、https://blog.csdn.net/junlong750/article/details/50945883

        2、http://commons.apache.org/proper/commons-jexl/

commons-jexl包可以将字符串转化为可执行的java代码,支持各种表达式运算,包括且、或、异或、取反以及加减乘除等各种运算,且支持动态加载类与方法,功能强大。

 

一、官方demo:

    // Create or retrieve an engine
    JexlEngine jexl = new JexlBuilder().create();
    
    // Create an expression
    String jexlExp = "foo.innerFoo.bar()";
    JexlExpression e = jexl.createExpression( jexlExp );
    
    // Create a context and add data
    JexlContext jc = new MapContext();
    jc.set("foo", new Foo() );
    
    // Now evaluate the expression, getting the result
    Object o = e.evaluate(jc);

二、实用demo:

1、通用工具类:

    //使用commons的jexl可实现将字符串变成可执行代码的功能
	public static Object convertToCode(String jexlExp,Map map){  
        JexlEngine jexl=new JexlEngine();  
        Expression 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);  
	}  

2、调用示例one:

public static void main(String[] args) {
		try {
			Map map=new HashMap(); 
			map.put("money",2100);  
			String expression="money>=2000&&money<=4000";  
			Object code = convertToCode(expression,map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

3、调用示例two:

public static void main(String[] args) {
		try {
			Map map=new HashMap();  
			map.put("testService",testService);  
			map.put("person",person);  
			String expression="testService.save(person)";  
			convertToCode(expression,map);  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 

三、示例代码基于commons-jexl-2.0版本,jar包下载可以去中央仓库免费下载

       http://mvnrepository.com/ 搜索commons-jexl即可

四、支持的逻辑表达式如下:

Operator Description
Boolean and The usual && operator can be used as well as the word and, e.g.
cond1 and cond2
and
cond1 && cond2
are equivalent
Boolean or The usual || operator can be used as well as the word or, e.g.
cond1 or cond2
and
cond1 || cond2
are equivalent
Boolean not The usual ! operator can be used as well as the word not, e.g.
!cond1
and
not cond1
are equivalent
Bitwise and The usual & operator is used, e.g.
33 & 4
, 0010 0001 & 0000 0100 = 0.
Bitwise or The usual | operator is used, e.g.
33 | 4
, 0010 0001 | 0000 0100 = 0010 0101 = 37.
Bitwise xor The usual ^ operator is used, e.g.
33 ^ 4
, 0010 0001 ^ 0000 0100 = 0010 0100 = 37.
Bitwise complement The usual ~ operator is used, e.g.
~33
, ~0010 0001 = 1101 1110 = -34.
Ternary conditional ?: The usual ternary conditional operator condition ? if_true : if_false operator can be used as well as the abbreviation value ?: if_false which returns the value if its evaluation is defined, non-null and non-false, e.g.
val1 ? val1 : val2
and
val1 ?: val2 
are equivalent.

NOTE: The condition will evaluate to false when it refers to an undefined variable or null for all JexlEngine flag combinations. This allows explicit syntactic leniency and treats the condition 'if undefined or null or false' the same way in all cases.

Equality The usual == operator can be used as well as the abbreviation eq. For example
val1 == val2
and
val1 eq val2
are equivalent.
  1. null is only ever equal to null, that is if you compare null to any non-null value, the result is false.
  2. Equality uses the java equals method
Inequality The usual != operator can be used as well as the abbreviation ne. For example
val1 != val2
and
val1 ne val2
are equivalent.
Less Than The usual < operator can be used as well as the abbreviation lt. For example
val1 < val2
and
val1 lt val2
are equivalent.
Less Than Or Equal To The usual <= operator can be used as well as the abbreviation le. For example
val1 <= val2
and
val1 le val2
are equivalent.
Greater Than The usual > operator can be used as well as the abbreviation gt. For example
val1 > val2
and
val1 gt val2
are equivalent.
Greater Than Or Equal To The usual >= operator can be used as well as the abbreviation ge. For example
val1 >= val2
and
val1 ge val2
are equivalent.
In or Match=~ The syntactically Perl inspired =~ operator can be used to check that a string matches a regular expression (expressed either a Java String or a java.util.regex.Pattern). For example "abcdef" =~ "abc.* returns true. It also checks whether any collection, set or map (on keys) contains a value or not; in that case, it behaves as an "in" operator. Note that arrays and user classes exposing a public 'contains' method will allow their instances to behave as right-hand side operands of this operator. "a" =~ ["a","b","c","d","e",f"] returns true.
Not-In or Not-Match!~ The syntactically Perl inspired !~ operator can be used to check that a string does not match a regular expression (expressed either a Java String or a java.util.regex.Pattern). For example "abcdef" !~ "abc.* returns false. It also checks whether any collection, set or map (on keys) does not contain a value; in that case, it behaves as "not in" operator. Note that arrays and user classes exposing a public 'contains' method will allow their instances to behave as right-hand side operands of this operator. "a" !~ ["a","b","c","d","e",f"] returns true.
Starts With=^ The =^ operator is a short-hand for the 'startsWith' method. For example, "abcdef" =^ "abc" returns true. Note that through duck-typing, user classes exposing a public 'startsWith' method will allow their instances to behave as left-hand side operands of this operator.
Not Starts With!^ This is the negation of the 'starts with' operator. a !^ "abc" is equivalent to !(a =^ "abc")
Ends With=$ The =$ operator is a short-hand for the 'endsWith' method. For example, "abcdef" =$ "def" returns true. Note that through duck-typing, user classes exposing an 'endsWith' method will allow their instances to behave as left-hand side operands of this operator.
Not Ends With!$ This is the negation of the 'ends with' operator. a !$ "abc" is equivalent to !(a =$ "abc")
Range.. This operator creates a 'range' of values (in the form of a java iterable). For example, for(var x: 1 .. 3) {} will loop 3 times with the value of 'x' being 1, 2 and 3.
Addition The usual + operator is used. For example
val1 + val2
Subtraction The usual - operator is used. For example
val1 - val2
Multiplication The usual * operator is used. For example
val1 * val2
Division The usual / operator is used, or one can use the div operator. For example
val1 / val2
or
val1 div val2
Modulus (or remainder) The % operator is used. An alternative is the mod operator. For example
5 mod 2
gives 1 and is equivalent to
5 % 2
Side-effect operators Some operators exist in side-effect forms. Their default behavior is to execute the operator and assign the left-hand side with the result. For instance a += 2 is equivalent to a = a + 2 The list of operators is:
  • +=
  • -=
  • *=
  • /=
  • %=
  • &=
  • |=
  • ^=
Negation The unary - operator is used. For example
-12
Array access Array elements may be accessed using either square brackets or a dotted numeral, e.g.
arr1[0]
and
arr1.0
are equivalent
Map access Map elements are accessed using square brackets, e.g.
map[0]; map['name']; map[var];
Note that
map['7']
and
map[7]
refer to different elements. Map elements with a numeric key may also be accessed using a dotted numeral, e.g.
map[0]
and
map.0
are equivalent.

 

 

 

 

你可能感兴趣的:(编程开发)