加载指定包的所有类
获取包所在路径 获取路径下的所有后缀为class的文件
1. 获取包所在路径
public static Set< Class< ? >> extractPackageClass ( String packageName) {
ClassLoader classLoader = getClassLoader ( ) ;
URL url = classLoader. getResource ( packageName. replace ( "." , "/" ) ) ;
if ( url == null) {
log. warn ( "unable to retrieve anything from package:" + packageName) ;
return null;
}
Set< Class< ? >> classSet = null;
if ( FILE_PROTOCOL. equalsIgnoreCase ( url. getProtocol ( ) ) ) {
classSet = new HashSet < Class< ? >> ( ) ;
File packageDirectory = new File ( url. getPath ( ) ) ;
extractClassFile ( classSet, packageDirectory, packageName) ;
}
return classSet;
}
public static ClassLoader getClassLoader ( ) {
return Thread. currentThread ( ) . getContextClassLoader ( ) ;
}
2. 获取路径下的所有后缀为class的文件
private static void extractClassFile ( Set< Class< ? >> classSet, File fileSource, String packageName) {
if ( ! fileSource. isDirectory ( ) ) {
return ;
}
File[ ] files = fileSource. listFiles ( new FileFilter ( ) {
@Override
public boolean accept ( File file) {
if ( file. isDirectory ( ) ) {
return true ;
} else {
String absoluteFilePath = file. getAbsolutePath ( ) ;
if ( absoluteFilePath. endsWith ( ".class" ) ) {
addToClassSet ( absoluteFilePath) ;
}
}
return false ;
}
private void addToClassSet ( String absoluteFilePath) {
absoluteFilePath = absoluteFilePath. replace ( File. separator, "." ) ;
String className = absoluteFilePath. substring ( absoluteFilePath. indexOf ( packageName) , absoluteFilePath. lastIndexOf ( "." ) ) ;
Class< ? > targetClass = loadClass ( className) ;
classSet. add ( targetClass) ;
}
} ) ;
if ( files != null) {
for ( File f: files) {
extractClassFile ( classSet, f, packageName) ;
}
}
}
public static Class< ? > loadClass ( String className) {
try {
return Class. forName ( className) ;
} catch ( ClassNotFoundException e) {
log. error ( "load class error:" , e) ;
throw new RuntimeException ( ) ;
}
}