By Shadowtrot

2014-02-04 05:14:34 8 Comments

(This question is similar to many questions I have seen but most are not specific enough for what I am doing)


The purpose of my program is to make it easy for people who use my program to make custom "plugins" so to speak, then compile and load them into the program for use (vs having an incomplete, slow parser implemented in my program). My program allows users to input code into a predefined class extending a compiled class packaged with my program. They input the code into text panes then my program copies the code into the methods being overridden. It then saves this as a .java file (nearly) ready for the compiler. The program runs javac (java compiler) with the saved .java file as its input.

My question is, how do I get it so that the client can (using my compiled program) save this java file (which extends my InterfaceExample) anywhere on their computer, have my program compile it (without saying "cannot find symbol: InterfaceExample") then load it and call the doSomething() method?

I keep seeing Q&A's using reflection or ClassLoader and one that almost described how to compile it, but none are detailed enough for me/I do not understand them completely.


@MadProgrammer 2014-02-04 05:46:43

Take a look at JavaCompiler

The following is based on the example given in the JavaDocs

This will save a File in the testcompile directory (based on the package name requirements) and the compile the File to a Java class...

package inlinecompiler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class InlineCompiler {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(64);
        sb.append("package testcompile;\n");
        sb.append("public class HelloWorld implements inlinecompiler.InlineCompiler.DoStuff {\n");
        sb.append("    public void doStuff() {\n");
        sb.append("        System.out.println(\"Hello world\");\n");
        sb.append("    }\n");

        File helloWorldJava = new File("testcompile/");
        if (helloWorldJava.getParentFile().exists() || helloWorldJava.getParentFile().mkdirs()) {

            try {
                Writer writer = null;
                try {
                    writer = new FileWriter(helloWorldJava);
                } finally {
                    try {
                    } catch (Exception e) {

                /** Compilation Requirements *********************************************************************************************/
                DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

                // This sets up the class path that the compiler will use.
                // I've added the .jar file that contains the DoStuff interface within in it...
                List<String> optionList = new ArrayList<String>();
                optionList.add(System.getProperty("java.class.path") + File.pathSeparator + "dist/InlineCompiler.jar");

                Iterable<? extends JavaFileObject> compilationUnit
                        = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
                JavaCompiler.CompilationTask task = compiler.getTask(
                /********************************************************************************************* Compilation Requirements **/
                if ( {
                    /** Load and execute *************************************************************************************************/
                    // Create a new custom class loader, pointing to the directory that contains the compiled
                    // classes, this should point to the top of the package structure!
                    URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});
                    // Load the class from the classloader by name....
                    Class<?> loadedClass = classLoader.loadClass("testcompile.HelloWorld");
                    // Create a new instance...
                    Object obj = loadedClass.newInstance();
                    // Santity check
                    if (obj instanceof DoStuff) {
                        // Cast to the DoStuff interface
                        DoStuff stuffToDo = (DoStuff)obj;
                        // Run it baby
                    /************************************************************************************************* Load and execute **/
                } else {
                    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
                        System.out.format("Error on line %d in %s%n",
            } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {

    public static interface DoStuff {

        public void doStuff();


Now updated to include suppling a classpath for the compiler and loading and execution of the compiled class!

@c4k 2017-01-02 15:12:57

I was wondering what can be the security issues if we compile user-input code and how to protect our system against that ? Thanks

@MadProgrammer 2017-01-02 20:03:33

@c4k Since the user has access to the entire API, they could pretty much do what they want, without going to the extent of having your own library implementation, you could sandbox the user and/or execute the code as an unprivileged user

@c4k 2017-01-03 11:15:39

@MadProgrammer thanks for the explanation. To go further I found this paragraph on Janino's website It might be worth reading before going deeper on this ;)

@Peter Lawrey 2016-02-11 23:18:34

I suggest using the Java Runtime Compiler library. You can give it a String in memory and it will compile and load the class into the current class loader (or one of your choice) and return the Class loaded. Nested classes are also loaded. Note: this works entirely in memory by default.


 // dynamically you can call
 String className = "mypackage.MyClass";
 String javaCode = "package mypackage;\n" +
                  "public class MyClass implements Runnable {\n" +
                  "    public void run() {\n" +
                  "        System.out.println(\"Hello World\");\n" +
                  "    }\n" +
 Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
 Runnable runner = (Runnable) aClass.newInstance();;

@CHEM_Eugene 2020-01-28 08:33:07

What if MyClass implements some interface which already exists at runtime? A can't get it work in Spring Boot application!

@Peter Lawrey 2020-02-13 18:43:49

@CHEM_Eugene You can't change a class which has already been loaded this way. You need to add it to a new ClassLoader.

Related Questions

Sponsored Content

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4050422 View
  • 3497 Score
  • 65 Answer
  • Tags:   java random integer

44 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

57 Answered Questions

[SOLVED] How to create a memory leak in Java?

42 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

53 Answered Questions

27 Answered Questions

[SOLVED] Java inner class and static nested class

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

27 Answered Questions

[SOLVED] How do I declare and initialize an array in Java?

  • 2009-07-29 14:22:27
  • bestattendance
  • 4506823 View
  • 2050 Score
  • 27 Answer
  • Tags:   java arrays

29 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1958790 View
  • 2271 Score
  • 29 Answer
  • Tags:   java arrays

Sponsored Content