Transform string into code in Java

前端 未结 4 1264
说谎
说谎 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:25

    The best way to do it is using the Scripting API as most answerers already pointed out. You can run JavaScript from there. If you want to dare more and try to run Java code (and get pointed at as an eretic) you can try to compile code with JavaCompiler and the run it using a class loader.

    BEWARE: This is one of the most ORRIFIC ways to use Java. You should use this only to debug and only as last hope. In no way at all you should use this in a production environment.

    This will create a DontTryThisAtHome.java file in your classpath. Remeber to use this strategy only for fun and very few other cases:

    public class MyClass{
        public static void main(String[] args) throws Exception {
            JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
            File jf = new File("DontTryThisAtHome.java");
            PrintWriter pw = new PrintWriter(jf);
            pw.println("public class DontTryThisAtHome{"
                    + "static final int score = " +  + ";"
                    + "public static void main(){}"
                    + "public int getValue(){"
                    + " return score<=0.7?0:score<=0.8?1: score<=0.9?2:3"
                    + "}
                    + "}");
        pw.close();
        Iterable fO = sjfm.getJavaFileObjects(jf);
        if(!jc.getTask(null,sjfm,null,null,null,fO).call()) {
            throw new Exception("compilation failed");
        }
        URL[] urls = new URL[]{new File("").toURI().toURL()};
        URLClassLoader ucl = new URLClassLoader(urls);
        Object o= ucl.loadClass("DontTryThisAtHome").newInstance();
        int result = (int) o.getClass().getMethod("getValue").invoke(o);
        ucl.close();
    }
    }
    

提交回复
热议问题