trung / InMemoryJavaCompiler

Utility class to compile java source code in memory
Apache License 2.0
266 stars 81 forks source link

Run compiled class in separate Java process #6

Open lfuelling opened 8 years ago

lfuelling commented 8 years ago

Hi @trung,

I'm using your library to compile code that's coming from a web interface. After compilation I'm running the compiled class to evaluate the output.

If a user inputs something like System.exit(0);, the server will crash. I tried to prevent this by running the compiled class in a separate process like this:

public static int exec(Class clazz) throws IOException,
            InterruptedException {
        String javaHome = System.getProperty("java.home");
        String javaBin = javaHome +
                File.separator + "bin" +
                File.separator + "java";
        String classpath = System.getProperty("java.class.path");
        String className = clazz.getCanonicalName();

        ProcessBuilder builder = new ProcessBuilder(
                javaBin, "-cp", classpath, className);

        Process process = builder.start();
        process.waitFor();
        return process.exitValue();
    }

The problem with this is that I'm getting a "Class not found" error everytime I try to run the compiled class like this.

Is it possible to run the compiled class in a separate process using another way?

trung commented 7 years ago

I think it's due to the your application class loader can't find the class which was dynamically compiled.

I need to try this myself but my thinking is that there should be additional step in your application to load the dynamic compiled class in the application class loader.