Custom class loaders and class identity
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A plugin system must load a new .class file from a folder while the program is running, and even run two versions side by side. The default loader cannot do that. What can you build instead?
Loading classes from a folder or JAR with URLClassLoader
URLClassLoader is a ready-made class loader that finds classes in a list of folders and JAR files, given as URLs. You create it with those URLs and a parent, call loadClass("Name"), and get a Class you can create objects from.
Example 1 · A discount plugin loaded at run time
import java.net.URL;import java.net.URLClassLoader;import java.nio.file.Files;import java.nio.file.Path;import java.util.Comparator;import java.util.stream.Stream;import javax.tools.JavaCompiler;import javax.tools.ToolProvider;
public class PluginDemo { // Shared contract: loaded once, by the application loader public interface DiscountPlugin { int discountPercent(int billAmount); }
public static void main(String[] args) throws Exception { Path pluginDir = Files.createTempDirectory("plugins"); Path source = pluginDir.resolve("FestDiscount.java"); Files.writeString(source, "public class FestDiscount implements PluginDemo.DiscountPlugin {\n" + " public int discountPercent(int bill) {\n" + " return bill >= 500 ? 20 : 10;\n" + " }\n" + "}\n");
// 2. Compile it into the plugin folder (needs a JDK, not just a JRE) JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); int status = javac.run(null, null, null, "-cp", System.getProperty("java.class.path"), "-d", pluginDir.toString(), source.toString()); System.out.println("Plugin compiled: " + (status == 0));
// 3. Load it by name from the folder URL[] urls = { pluginDir.toUri().toURL() }; try (URLClassLoader loader = new URLClassLoader("plugins", urls, PluginDemo.class.getClassLoader())) { Class<?> cls = loader.loadClass("FestDiscount"); System.out.println("Loaded " + cls.getName() + " with loader " + cls.getClassLoader().getName());
DiscountPlugin plugin = (DiscountPlugin) cls.getDeclaredConstructor().newInstance(); System.out.println("Bill Rs 800 -> " + plugin.discountPercent(800) + "% off"); System.out.println("Bill Rs 300 -> " + plugin.discountPercent(300) + "% off"); }
try (Stream<Path> files = Files.walk(pluginDir)) { files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); } System.out.println("Plugin folder deleted: " + !Files.exists(pluginDir)); }}Plugin compiled: true Loaded FestDiscount with loader plugins Bill Rs 800 -> 20% off Bill Rs 300 -> 10% off Plugin folder deleted: true
What this code does
FestDiscountdid not exist whenPluginDemowas compiled. Thepluginsloader finds it in the temporary folder and defines it, andgetDeclaredConstructor().newInstance()creates an object.- The cast to
DiscountPluginworks because the plugin loader's parent is the application loader: both sides use the oneDiscountPluginclass thatappdefined. Thetry-with-resources closes the loader before the folder is deleted.
The main program cannot mention the plugin class in its source, because it does not exist at compile time. So both sides agree on a shared interface that the parent loader provides. The program casts the new object to that interface and calls it. URLClassLoader keeps its JAR files open, so close it when you are done (it is Closeable, Java 7+). On Windows an open JAR cannot be deleted or replaced.
ToolProvider.getSystemJavaCompiler() is javac as a Java API. It exists only when you run on a JDK (not a bare JRE); here it stands in for a plugin someone else compiled.Same class name, two loaders: two different classes
Class identity in the JVM means a class is identified by its full name together with its defining class loader. The same file loaded by two loaders gives two different classes.
Inside the JVM, a class is identified by its full name and its defining loader: the loader that called defineClass for it. Load the same Ticket.class file through two loaders that both define it themselves, and you get two separate classes.
Example 2 · One class file, three different classes
import java.net.URL;import java.net.URLClassLoader;
public class TwoLoadersDemo { public static class Ticket { public String pnr = "PNR-4521"; }
public static void main(String[] args) throws Exception { // The folder (or JAR) this program's own classes came from URL myClasses = TwoLoadersDemo.class.getProtectionDomain().getCodeSource().getLocation(); ClassLoader platform = ClassLoader.getPlatformClassLoader(); // cannot see our classes
try (URLClassLoader loaderA = new URLClassLoader("loaderA", new URL[] { myClasses }, platform); URLClassLoader loaderB = new URLClassLoader("loaderB", new URL[] { myClasses }, platform)) {
Class<?> fromApp = Ticket.class; Class<?> fromA = loaderA.loadClass("TwoLoadersDemo$Ticket"); Class<?> fromB = loaderB.loadClass("TwoLoadersDemo$Ticket");
boolean sameNames = fromA.getName().equals(fromB.getName()) && fromA.getName().equals(fromApp.getName()); System.out.println("Names equal: " + sameNames); System.out.println("Loaders: " + fromApp.getClassLoader().getName() + ", " + fromA.getClassLoader().getName() + ", " + fromB.getClassLoader().getName()); System.out.println("fromA == fromB: " + (fromA == fromB)); System.out.println("fromA == Ticket.class: " + (fromA == fromApp)); System.out.println("loaderA asked again: " + (fromA == loaderA.loadClass("TwoLoadersDemo$Ticket"))); } }}Names equal: true Loaders: app, loaderA, loaderB fromA == fromB: false fromA == Ticket.class: false loaderA asked again: true
What this code does
- Both new loaders read the same
Ticket.classfile from the program's own folder. Their parent is the platform loader, which cannot see that folder, so each defines its own copy. With the app's ownTicket, that makes three classes namedTwoLoadersDemo$Ticket. - Asking
loaderAagain returns its cached class, so within one loader the class is unique.TwoLoadersDemo$Ticketis how a nested class is named in a class file.
They have equal names, separate static fields and separate Class objects. This only happens when each loader finds the class itself. If a loader delegates and its parent finds the class, you get the parent's class, and nothing is duplicated. The trick to create two copies is a parent that cannot see the class, such as the platform loader.
One loader never defines the same name twice: a second defineClass for Notice in the same loader throws LinkageError: ... attempted duplicate class definition for Notice.
ClassCastException between classes from different loaders
Because the two Ticket classes are different, an object of one is not an instance of the other. instanceof returns false, and a cast throws one of Java's most confusing messages, shown below.
Example 3 · "Ticket cannot be cast to Ticket" and the fix
import java.net.URL;import java.net.URLClassLoader;
public class CastAcrossLoadersDemo { public static class Ticket { public String pnr = "PNR-4521";
public String toString() { return "Ticket " + pnr; } }
public static void main(String[] args) throws Exception { URL myClasses = CastAcrossLoadersDemo.class.getProtectionDomain().getCodeSource().getLocation(); String name = "CastAcrossLoadersDemo$Ticket";
try (URLClassLoader other = new URLClassLoader("other", new URL[] { myClasses }, ClassLoader.getPlatformClassLoader())) { Object fromOther = other.loadClass(name).getDeclaredConstructor().newInstance(); System.out.println("toString works: " + fromOther); System.out.println("instanceof Ticket: " + (fromOther instanceof Ticket)); try { Ticket t = (Ticket) fromOther; System.out.println("cast worked: " + t.pnr); } catch (ClassCastException e) { String msg = e.getMessage(); System.out.println("ClassCastException: " + msg.substring(0, msg.indexOf(" ("))); } }
// The fix: the parent is the app loader, so delegation returns the app's Ticket try (URLClassLoader shared = new URLClassLoader("shared", new URL[] { myClasses }, CastAcrossLoadersDemo.class.getClassLoader())) { Object fromShared = shared.loadClass(name).getDeclaredConstructor().newInstance(); Ticket t = (Ticket) fromShared; System.out.println("with app loader as parent, cast worked: " + t.pnr); } }}toString works: Ticket PNR-4521 instanceof Ticket: false ClassCastException: class CastAcrossLoadersDemo$Ticket cannot be cast to class CastAcrossLoadersDemo$Ticket with app loader as parent, cast worked: PNR-4521
What this code does
- Methods called through
Object, liketoString, work fine. But the object belongs to theotherloader'sTicket, soinstanceofisfalseand the cast fails. The program prints the message only up to(, because the rest contains a hash code that changes on every run. - With the application loader as parent,
shareddelegates first,appalready hasTicket, and the same class comes back. Shared types must come from one common parent.
class Ticket cannot be cast to class Ticket (Ticket is in unnamed module of loader 'loaderA' @5a07e868; Ticket is in unnamed module of loader 'app') The names match, but the loaders in brackets do not. The fix is to load shared types once, in a parent that both sides delegate to. Package-private access breaks the same way: two classes in the same package but from different loaders are in different runtime packages, and the JVM throws IllegalAccessError.
- Real message on JDK 21:
class FestDiscount cannot access its superinterface DiscountPlugin (FestDiscount is in unnamed module of loader 'plugins' ...; DiscountPlugin is in unnamed module of loader 'app'). - That is why the shared interface in Example 1 is
public: a package-private one fails as soon as the plugin is defined.
Where custom loaders are used: plugins, servers and reloading
Custom loaders sit under many tools you use every day. A plugin system (IDEs, build tools) gives each plugin its own loader.
Example 4 · Hot reload: a new loader for each version
import java.net.URL;import java.net.URLClassLoader;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.function.IntUnaryOperator;import java.util.stream.Stream;import javax.tools.ToolProvider;
public class HotReloadDemo { static Path dir; static List<URLClassLoader> loaders = new ArrayList<>();
// Write FeeRule.java with the given hostel fee, compile it, load it with a NEW loader static IntUnaryOperator loadVersion(int version, int hostelFee) throws Exception { Path folder = dir.resolve("v" + version); Files.createDirectories(folder); Path src = folder.resolve("FeeRule.java"); Files.writeString(src, "public class FeeRule implements java.util.function.IntUnaryOperator {\n" + " public int applyAsInt(int tuition) {\n" + " return tuition + " + hostelFee + ";\n" + " }\n" + "}\n"); ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", folder.toString(), src.toString());
URLClassLoader loader = new URLClassLoader("rules-v" + version, new URL[] { folder.toUri().toURL() }, HotReloadDemo.class.getClassLoader()); loaders.add(loader); Class<?> c = loader.loadClass("FeeRule"); System.out.println("Loaded FeeRule with loader " + c.getClassLoader().getName()); return (IntUnaryOperator) c.getDeclaredConstructor().newInstance(); }
public static void main(String[] args) throws Exception { dir = Files.createTempDirectory("reload");
IntUnaryOperator rule = loadVersion(1, 40000); System.out.println("Total fee: Rs " + rule.applyAsInt(85000)); Class<?> oldClass = rule.getClass();
// The hostel fee changes while the app keeps running rule = loadVersion(2, 45000); System.out.println("Total fee: Rs " + rule.applyAsInt(85000)); System.out.println("Two different FeeRule classes: " + (oldClass != rule.getClass()));
for (URLClassLoader l : loaders) { l.close(); } try (Stream<Path> files = Files.walk(dir)) { files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); } }}Loaded FeeRule with loader rules-v1 Total fee: Rs 125000 Loaded FeeRule with loader rules-v2 Total fee: Rs 130000 Two different FeeRule classes: true
What this code does
- Version 2 is a different class file with the same name. It cannot replace version 1 inside
rules-v1, so a fresh loaderrules-v2defines it. The running program switches to the new object and never restarts. - The shared type is
IntUnaryOperator, a JDK interface from the bootstrap loader, so the cast works for every version. Once nothing points to the old object, its class orrules-v1, the garbage collector may unload the old version.
Application servers such as Tomcat give each web app its own loader, so two apps can use different versions of one library and be redeployed separately. Hot reload tools, such as Spring Boot DevTools, put your changing classes in a throwaway loader and create a new one on each restart. You cannot change a class that is already loaded. Reloading always means a new loader that defines the new version, while the old version stays in the old loader.
A class can be unloaded only when its loader, all its classes and all their objects are unreachable. Classes from the built-in loaders are never unloaded. If anything still points into an old loader, such as a static cache in a parent class or a running thread, the whole loader stays in memory (in Metaspace on HotSpot). Repeated redeploys then leak memory: a class loader leak.
Next step
Check your understanding
11 quick questions