Created
December 18, 2015 06:22
-
-
Save ochinchina/ca424784c923a36eb183 to your computer and use it in GitHub Desktop.
scan all the classes under a specific package recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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