mercredi 1 février 2017

Java runtime compiler using reflections not working properly

I have a JavaFX app where there is an editor. In the editor, the user will be able to write java code and I have a button to compile this code and run the main method. For example the editor will contain this code:

public class Test {
    public static void main(String[] args) {
        System.out.println("hello");
    }
}

The button on click, will run this code:

runButton.setOnAction(e -> {
        compiler.set(editor.getText());
        try {
            compiler.createFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        compiler.compile();
        compiler.run();

    });

In the compiler class, there is the following implementation:

public class CodeCompiler {

public String className;
public String code;

public void set(String code) {
    try {
        this.className = code.substring(code.indexOf(" class ") + 6, code.indexOf(" {")).trim();
    } catch(StringIndexOutOfBoundsException e) {

    }
    this.code = code;
}

public void createFile() throws IOException {
    PrintWriter pw = new PrintWriter("speech2code/src/main/java/" + className + ".java");
    pw.close();
    FileWriter writer = new FileWriter("speech2code/src/main/java/" + className + ".java", true);
    writer.write(code);
    writer.flush();
    writer.close();
}

public void compile() {
    File file = new File("speech2code/src/main/java/" + className + ".java");
    File classFile = new File("speech2code/src/main/java/" + className + ".class");
    classFile.delete(); // delete class file f it exists
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, file.getPath());
}

public void run() {

    Class<?> cls = null;
    try {
        cls = Class.forName(className);
        System.out.println(cls == null);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Method meth = null;
    try {
        meth = cls.getMethod("main", String[].class);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    String[] params = null;
    try {
        meth.invoke(null, (Object) params);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}


}

Now the code above successfully creates the java file, class file and runs correctly the first time. Now when I change the editor code to print something else, it outputs the result of the first time the code was running. So, in this case, it will still print 'hello' instead of whatever it's current value.

Any problem what might be wrong? Thanks!





Aucun commentaire:

Enregistrer un commentaire