Dynamically compile a Java source file and execute a method on it

You can use the package sun.tools.javac located in JDK/lib/tools.jar. Make sure you add this Jar file to your classpath!

When your invoke compile, you pass a String array containing the file to compile, and optionally also other compile options, eg. new String[] { “-classpath”, “c:mylibs”, “Test.java” }.

Main.java:

import java.lang.reflect.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
      sun.tools.javac.Main compiler = 
             new sun.tools.javac.Main(baos, "javac"); 
      boolean compileOk = compiler.compile(new String[] {"Test.java"}); 
 
      System.out.println("Compiled ok? " + compileOk);
 
      if (compileOk) {
         Class c = Class.forName("Test");
         // create a new instance of Test
         Object o = c.newInstance();
  
         // invoke a method on it
         Method m = c.getMethod("method", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      else {
         System.out.println("Error compiling");
      }
   }
}

Test.java:

public class Test
{
   public void method() {
      System.out.println("Method in class Test executed!");
   }
}

Running Main outputs:

Compiled ok? true
Method in class Test executed!