on-the-fly compilation with java

It is sometimes necessary to compile java code "on the fly", it is possible with the following snippets

Compiling by adding some jars from a folder in the classpath

To add the jars contained in a directory

Building the classpath

File[] files = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        });
String cp = ".";
for (File jarFile : files) {
    cp += File.pathSeparatorChar + jarFile.getAbsolutePath();
}

Getting and running the compiler

    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, "-classpath", cp, "Test.java");

Adding jars to the current classpath

            ClassLoader clLoader = ClassLoader.getSystemClassLoader();
               // Get the ClassLoader class 
            ClassLoader cl = ClassLoader.getSystemClassLoader();
            Class<?> clazz = cl.getClass();

            // Get the protected addURL method from the parent URLClassLoader class
            Method method = clazz.getSuperclass().getDeclaredMethod("addURL", new Class[] {URL.class});

            // Run projected addURL method to add JAR to classpath
            method.setAccessible(true);
            for (File jar : files) {
                method.invoke(cl, new Object[] {jar.toURI().toURL()});
            }

Adding a class to the current classpath

            final URLClassLoader classLoader = new URLClassLoader(new URL[] { new File("test.java").toURI().toURL()});

            final Class<?> cls = classLoader.loadClass("generated" + testName);

Previous Post