Java将字符串转换成可执行代码

1. 添加依赖

<dependency>
    <groupId>org.apache.commons</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 (Checker.isNotEmpty(map)) {
        map.forEach(context::set);
    }
    return expression.evaluate(context);
}

3. 测试

@Test
public void testExecuteExpression() {
    Map<String, Object> map = new HashMap<>();
    map.put("alive", "coding every day");
    map.put("out", System.out);
    String expression = "out.print(alive)";
    executeExpression(expression, map);
    // ReflectUtils.executeExpression(expression, map);
}
// output:coding every day
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页