Transform string into code in Java

前端 未结 4 1311
说谎
说谎 2021-02-06 08:47

I got a strange case. In the given database, I got a record that has a VARCHAR field, so in my entity model I added this field, plus getters and setters. Now is the

4条回答
  •  离开以前
    2021-02-06 09:05

    Look at the java scripting API

    int eval(String code) {
        code = "function f () {" + code + "} f()"; // Or otherwise
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        engine.put("score", 1.4);
        Number num = (Number) engine.eval(code);
        return num.intValue();
    }
    

    Here I assumed, that JavaScript syntax is possible; had to fill in score, you might somewhere intercept all unknown free variables.

提交回复
热议问题