The Unbearable Lightness of Java

Class finder and scanner

Finding a class or a resource on classpath is very useful in some usecases like during configuration process of some framework. Jodd provides an abstract class ClassFinder that contains internal logic (based on FindFile) for finding classes and resources on provided classpath. ClassFinder is able to scan JARs, filter entities by including and/or excluding some and so on. When matched class or resource (i.e. entry) is found, callback method is invoked.

For scanning files and folders, see file finder.

Besides locating classes and resources, ClassFinder may open it's input stream by using InputStreamProvider that is passed to callback method, so callback method may read actual content of class or resource. Once opened, InputStream does not have to be closed in callback method, since ClassFinder does that.

ClassFinder is supposed to be used by some configurator, therefore not all methods are made public. ClassFinderis used internally by many Jodd frameworks, for automatic configurations. It usually reads classes on classpath and scans them for some annotations.

ClassScanner

For more convenient on-place usage, there is ClassScanner. It extends ClassFinder and offers some public scanning methods and fluent interface. Here is the usage example:

ClassScanner cs = new ClassScanner() {
	@Override
	protected void onClassName(EntryData entryData) {
		InputStream inputStream = entryData.openInputStream();
		byte[] bytes = StreamUtil.readAvailableBytes(inputStream);
		System.out.println("---> " + entryData.getName() + ':' + entryData.getArchiveName() + "\t\t" + bytes.length);
	}
};
cs.includeResources(true).scan("/some/classpath");