Compile Java source code

In this chapter you will learn:

  1. How to compile Java source code dynamically
  2. How to compile and run a Java source dynamically

Compile Java source code dynamically

The following code compile a Java source file dynamically. It creates a String object containing a simple Java hello world applications. Then it calls ToolProvider.getSystemJavaCompiler() to create a JavaCompiler object and loads the input file and set class as the output type. Finally calls the getTask method to do the compilcation.

import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
//from j a  va 2  s.c om
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public class Main{
  public static void main(String[] args)throws Exception {
      File sourceFile = new File("generated/Hello.java");
      FileWriter writer = new FileWriter(sourceFile);
      writer.write("public class Hello{ \n" + " public void doit() { \n"
          + "   System.out.println(\"Hello world\") ;\n" + " }\n" + "}");
      writer.close();

      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      StandardJavaFileManager fileManager = compiler.getStandardFileManager(
          null, null, null);

      fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays
          .asList(new File("generated/")));
      // Compile the file
      boolean success = compiler.getTask(null, fileManager, null, null, null,
          fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)))
          .call();
      fileManager.close();
  }
}

Compile Java source and run it dynamically

The first part of the following code is identical to the code above. After compiling the source code it runs the class dynamically with Java reflection.

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
//from jav a2s  . c  om
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public class Main{
  public static void main(String[] args)throws Exception {
      File sourceFile = new File("generated/Hello.java");
      FileWriter writer = new FileWriter(sourceFile);
      writer.write("public class Hello{ \n" + " public void doit() { \n"
          + "   System.out.println(\"Hello world\") ;\n" + " }\n" + "}");
      writer.close();

      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      StandardJavaFileManager fileManager = compiler.getStandardFileManager(
          null, null, null);

      fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays
          .asList(new File("generated/")));
      // Compile the file
      boolean success = compiler.getTask(null, fileManager, null, null, null,
          fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)))
          .call();
      fileManager.close();
      runIt();
  }

  @SuppressWarnings("unchecked")
  public static void runIt() {
    try {
      Class params[] = {};
      Object paramsObj[] = {};
      Class thisClass = Class.forName("Hello");
      Object iClass = thisClass.newInstance();
      Method thisMethod = thisClass.getDeclaredMethod("doit", params);
      thisMethod.invoke(iClass, paramsObj);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is a Timer
  2. Set up a timer
  3. How to cancel a timer
  4. Schedule a task that executes once every second
Home » Java Tutorial » Utility Classes
Java standard stream
Java system property get and set
Current time in millis second and nano second
Random UUID
JVM memory
JVM garbage collector
JVM shutting down
Processor count
OS system commands
Random class
Random value
Random value range
Compile Java source code
Timer and TimerTask