Barron of Blog Wife, Kids, and the Pursuit of Happiness

2Sep/099

Java: Reflecting to Get All Classes in a Package

It took me a little while to figure out that Java doesn't provide a way to reflect an entire package. In other words, there is no built-in way for me to dynamically retrieve a list of all the classes in a given package in Java through reflection. So I wrote my own method to do it.

Since it took a bit of googling and effort, I thought it would be nice to share the convenience method I wrote with the world. Enjoy:

/**
 * Given a package name, attempts to reflect to find all classes within the package
 * on the local file system.
 * 
 * @param packageName
 * @return
 */
private static Set<Class> getClassesInPackage(String packageName) {
	Set<Class> classes = new HashSet<Class>();
	String packageNameSlashed = "/" + packageName.replace(".", "/")
	// Get a File object for the package
	URL directoryURL = Thread.currentThread().getContextClassLoader().getResource(packageNameSlashed);
	if (directoryURL == null) {
		LOG.warn("Could not retrieve URL resource: " + packageNameSlashed);
		return classes;
	}

	String directoryString = directoryURL.getFile();
	if (directoryString == null) {
		LOG.warn("Could not find directory for URL resource: " + packageNameSlashed);
		return classes;
	}

	File directory = new File(directoryString);
	if (directory.exists()) {
		// Get the list of the files contained in the package
		String[] files = directory.list();
		for (String fileName : files) {
			// We are only interested in .class files
			if (fileName.endsWith(".class")) {
				// Remove the .class extension
				fileName = fileName.substring(0, fileName.length() - 6);
				try {
					classes.add(Class.forName(packageName + "." + fileName));
				} catch (ClassNotFoundException e) {
					LOG.warn(packageName + "." + fileName + " does not appear to be a valid class.", e);
				}
			}
		}
	} else {
		LOG.warn(packageName + " does not appear to exist as a valid package on the file system.");
	}
	return classes;
}
Filed under: dev, geek Leave a comment
  • Janice

    nerd.

  • jpucci

    Finally! I've been trying to do this for months now! :)

  • http://mike.shannonandmike.net Mike B.

    Ha ha ha – you two are funny. But when that one developer nerd who was having the same problem finds this page in google he will be very thankful… I hope :)

  • jpucci

    Finally! I've been trying to do this for months now! :)

  • http://mike.shannonandmike.net Mike B.

    Ha ha ha – you two are funny. But when that one developer nerd who was having the same problem finds this page in google he will be very thankful… I hope :)

  • Jacques Ramsden

    Problem 1 : missing ‘;’ at the end of line 10

  • Jacques Ramsden

    Problem 2 : You are adding a leading ‘/’ does not find the dir if the leading ‘/’ is there so the line should look like

    String packageNameSlashed = packageName.replace(".", "/");

  • Stephen Demanuele

    I am thankful for this. being new to java, i did not know where to start.

    i am having trouble understanding what should ‘packageName’ be… just the name of the package is not enough, it has to be qualified by its directory location.
    Let’s say i have a project, which contains a package called myPackage. Project is saved at c:usersuserAworkspacemyProject.

    How do I point to myPackage ? i tried myProjectsrcmyPackage, and a dozen other combinations. Any pointers ?
    thank you

  • 3thm4n

    This helped me.