Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Created December 18, 2015 06:22
Show Gist options
  • Save ochinchina/ca424784c923a36eb183 to your computer and use it in GitHub Desktop.
Save ochinchina/ca424784c923a36eb183 to your computer and use it in GitHub Desktop.
scan all the classes under a specific package recursively
import java.io.File;
import java.net.URL;
public class ClassScanner {
@FunctionalInterface
public static interface ClassProcessor {
void processClass( Class clazz ) ;
}
public static void scan( String packageName, ClassProcessor classProcessor ) {
URL scannedUrl = Thread.currentThread().getContextClassLoader().getResource(packageName.replace( '.', '/'));
if( scannedUrl != null ) {
File scannedDir = new File(scannedUrl.getFile());
for (File file : scannedDir.listFiles()) {
scan( file, packageName, classProcessor );
}
}
}
private static void scan(File file, String packageName, ClassProcessor classProcessor) {
String resource = packageName + (packageName.isEmpty() ?"": ".") + file.getName();
if( file.isDirectory() ) {
for( File child: file.listFiles() ) {
scan( child, resource, classProcessor );
}
} else if( file.getName().endsWith( ".class")) {
String className = resource.substring( 0, resource.length() - ".class".length() );
try {
classProcessor.processClass( Class.forName( className ));
} catch (ClassNotFoundException e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment