Skip to content

Instantly share code, notes, and snippets.

@Sciss
Last active December 16, 2017 19:02
Show Gist options
  • Save Sciss/aca5f00a3f2a96b0077f51ea311c469e to your computer and use it in GitHub Desktop.
Save Sciss/aca5f00a3f2a96b0077f51ea311c469e to your computer and use it in GitHub Desktop.
import java.io.File
// quick semi-autotranslation from a Java snippet on SO
// get all classes with a package prefix
def getClasses(packageName: String): List[Class[_]] = {
val classLoader = Thread.currentThread.getContextClassLoader
assert(classLoader != null)
val path = packageName.replace('.', '/')
val resources = classLoader.getResources(path)
var dirs = List.empty[File]
while (resources.hasMoreElements) {
val resource = resources.nextElement
dirs ::= new File(resource.getFile)
}
var classes = List.empty[Class[_]]
for (directory <- dirs) {
classes :::= findClasses(directory, packageName)
}
classes
}
private def findClasses(directory: File, packageName: String): List[Class[_]] = {
if (!directory.exists) return Nil
var classes = List.empty[Class[_]]
val files = directory.listFiles
for (file <- files) {
if (file.isDirectory) {
assert(!file.getName.contains("."))
classes :::= findClasses(file, packageName + "." + file.getName)
}
else if (file.getName.endsWith(".class")) {
classes ::= Class.forName(packageName + '.' + file.getName.substring(0, file.getName.length - 6))
}
}
classes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment