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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章