Dynamically loading and creating a class from a JAR

For this example, let’s create a JAR file called testjar.jar containing only one class in a package esus.testpackage. Create a directory structure:

   esus
     |
     +--- testpackage
               |
               +-------- TestClass.java

TestClass.java:

package esus.testpackage;
 
public class TestClass
{
   public void testMethod() {
      System.out.println("testMethod() called!");
   }
}

Compile and create a JAR file:

   javac esustestpackageTestClass.java
   jar cvf testjar.jar esus

Let’s not add this JAR file to the classpath, but dynamically use it to load a class and execute a method on it. For this purpose, use the URLClassLoader which takes a set of URLs pointing to JARs or directories.

Main.java:

import java.lang.reflect.*;
import java.net.*;
  
public class Main {
   public static void main(String[] args) {
      try {
         URL []urls = new URL[] { new URL("file:testjar.jar") };
 
         ClassLoader cl = URLClassLoader.newInstance(urls);
 
         // load class 
         Class c = cl.loadClass("esus.testpackage.TestClass");
 
         // create instance of class esus.testpackage.TestClass
         Object o = c.newInstance();
 
         // execute method testMethod
         Method m = o.getClass().getMethod("testMethod", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

outputs:

testMethod() called!