好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现字符串转换成可执行代码的方法

使用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

查看更多关于Java实现字符串转换成可执行代码的方法的详细内容...

  阅读:53次