public static Collection < Class < ? > > getClasses ( String ... packageNames ) { List < Class < ? > > classes = new ArrayList <> ( ) ; for ( String packageName : packageNames ) { final String packagePath = packageName . replace ( ' ' , ' ' ) ; final String packagePrefix = packageName + ' ' ; List < URL > packageUrls = getResources ( packagePath ) ; for ( URL packageUrl : packageUrls ) { if ( packageUrl . getProtocol ( ) . equals ( "jar" ) ) { log . debug ( "Scanning jar {} for classes" , packageUrl ) ; try { String jar = packageUrl . toString ( ) . substring ( "jar:" . length ( ) ) . split ( "!" ) [ 0 ] ; File file = new File ( new URI ( jar ) ) ; try ( JarInputStream is = new JarInputStream ( new FileInputStream ( file ) ) ) { JarEntry entry = null ; while ( ( entry = is . getNextJarEntry ( ) ) != null ) { if ( ! entry . isDirectory ( ) && entry . getName ( ) . endsWith ( ".class" ) ) { String className = entry . getName ( ) . replace ( ".class" , "" ) . replace ( ' ' , ' ' ) ; if ( className . startsWith ( packagePrefix ) ) { Class < ? > aClass = getClass ( className ) ; classes . add ( aClass ) ; } } } } } catch ( URISyntaxException | IOException e ) { throw new FathomException ( e , "Failed to get classes for package '{}'" , packageName ) ; } } else { log . debug ( "Scanning filesystem {} for classes" , packageUrl ) ; log . debug ( packageUrl . getProtocol ( ) ) ; try ( InputStream is = packageUrl . openStream ( ) ) { Preconditions . checkNotNull ( is , "Package url %s stream is null!" , packageUrl ) ; try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { classes . addAll ( reader . lines ( ) . filter ( line -> line != null && line . endsWith ( ".class" ) ) . map ( line -> { String className = line . replace ( ".class" , "" ) . replace ( ' ' , ' ' ) ; try { Class < ? > aClass = getClass ( packagePrefix + className ) ; return aClass ; } catch ( Exception e ) { log . error ( "Failed to find {}" , line , e ) ; } return null ; } ) . collect ( Collectors . toList ( ) ) ) ; } } catch ( IOException e ) { throw new FathomException ( e , "Failed to get classes for package '{}'" , packageName ) ; } } } } return Collections . unmodifiableCollection ( classes ) ; }
Returns the list of all classes within a package .