使用commons的jexl可實現將字符串變成可執行代碼的功能,我寫了一個類來封裝這個功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import java.util.map; import org.apache.commons.jexl2.expression; import org.apache.commons.jexl2.jexlcontext; import org.apache.commons.jexl2.jexlengine; import org.apache.commons.jexl2.mapcontext; /** * 動態加載方法 * */ public class dymethodutil { public static object invokemethod(string jexlexp,map<string,object> 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); } } |
調用
1
2
3
4
5
|
map<string,object> map= new hashmap<string,object>(); map.put( "testservice" ,testservice); map.put( "person" ,person); string expression= "testservice.save(person)" ; dymethodutil.invokemethod(expression,map); |
以上這篇java實現字符串轉換成可執行代碼的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/u013410747/article/details/51791394