Convert String to Code

前端 未结 18 968
轮回少年
轮回少年 2020-11-22 09:27

I want to know if there is any way to convert a String to Java compilable code.

I have a comparative expression saved in a database field. I want to re

18条回答
  •  春和景丽
    2020-11-22 09:55

    If you are using Java 6, you could try the Java Compiler API. At its core is the JavaCompiler class. You should be able to construct the source code for your Comparator object in memory.

    Warning: I have not actually tried the code below as the JavaCompiler object is not available on my platform, for some odd reason...

    Warning: Compiling arbitrary Java code can be hazardous to your health.

    Consider yourself warned...

    String comparableClassName = ...; // the class name of the objects you wish to compare
    String comparatorClassName = ...; // something random to avoid class name conflicts
    String source = "public class " + comparatorClassName + " implements Comparable<" + comparableClassName + "> {" +
                    "    public int compare(" + comparableClassName + " a, " + comparableClassName + " b) {" +
                    "        return " + expression + ";" +
                    "    }" +
                    "}";
    
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    
    /*
     * Please refer to the JavaCompiler JavaDoc page for examples of the following objects (most of which can remain null)
     */
    Writer out = null;
    JavaFileManager fileManager = null;
    DiagnosticListener diagnosticListener = null;
    Iterable options = null;
    Iterable classes = null;
    Iterable compilationUnits = new ArrayList();
    compilationUnits.add(
        new SimpleJavaFileObject() {
            // See the JavaDoc page for more details on loading the source String
        }
    );
    
    compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits).call();
    
    Comparator comparator = (Comparator) Class.forName(comparableClassName).newInstance();
    

    After this, you just have to store the appropriate Java expression in your database field, referencing a and b.

提交回复
热议问题