Java Compiler API - Compile Code to a File and Load it using URLClassLoader

[Updated: Jan 23, 2016, Created: Dec 27, 2015]

In the previous example we saw how to compile java sources from string objects and load it using reflection. In this example we are going to show how to load the compiled code using URLClassLoader.

Steps are similar to the last example, except for we are creating output directory under user directory, retrieved as System.getProperty("user.dir"), using the same directory to output the compiled class using fileManager.setLocation and loading the class from the directory using URLClassLoader. Now we don't have to pre set a class path for the code to work.

Running the packaged jar creates the output folder (compiledClasses) at the same location

    D:\compiler-url-loader-example\target>java -cp

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Java Compiler Url Loader Example Select All Download
  • compiler-url-loader-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also