Close

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

[Last Updated: Jan 23, 2016]

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
          compiler-url-loader-example-1.0-SNAPSHOT.jar
                  com.logicbig.example.StringCompilation
    testing

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
                • StringCompilation.java

    See Also