记录一下java中怎么执行字符串中的代码块:

1、需要引入jar包


		<dependency>
			<groupId>org.apachemons</groupId>
			<artifactId>commons-jexl3</artifactId>
			<version>3.1</version>
		</dependency>

2、通用代码块提供代码执行功能

private static JexlEngine jexlEngine = new Engine();
public static Object executeExpression(String jexlExpression, Map<String, Object> map) {
		JexlExpression expression = jexlEngine.createExpression(jexlExpression);
		JexlContext context = new MapContext();
		if (map!=null&&!map.isEmpty()) {
			map.forEach(context::set);
		}
		return expression.evaluate(context);
	}

3、调用代码块

	Map<String, Object> map = new HashMap<>();
    map.put("newDate", new Date());//变量需要通过map注入
	map.put("OAUtils", new OAUtils());//类方法需要map注入
	String expression = "OAUtils.getMonthEnd(newDate)";
	Object bb = executeExpression(expression, map);

 

更多推荐

java中怎么执行字符串中的代码