← back to the blog


Preloading Java classes in a package (from both JAR archives and filesystem)

Posted
on 2007-11-10

The problem with Java's loading of classes on demand is that it's non trivial to implement a mechanism for dynamic discovery of new classes in packages. If we only want to drop new classes into a package, and don make any further modifications in the code and application configuration (e.g. properties), then we have no other choice but to do dirty tricks with traversing the package's file structure to discover the .class files.

This requires two different code paths for class files in JAR archives and in the filesystem - that's because the JAR archive is a ZIP file and doesn't contain a tree structure of directories. Instead, it contains a flat listing of all contents. So the getResource() method is unable to give us a File object which isDirectory() in the case of a JAR archive.

I've implemented a ClassPreloader class that provides a convenient preloadCurrentPackageClasses() method that handles both cases gracefully.

 

You'll find the source here.