Created
June 22, 2024 05:35
-
-
Save umbum/4080b66c3618410b57b46efab38f83b0 to your computer and use it in GitHub Desktop.
ClassNameExtractor
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
class ClassNameExtractor() { | |
fun extractClasses() { | |
val prefixDir = "/Users/user/Sources/my/external/src/main/kotlin/" | |
val packages = getNestedDirectoryPaths( | |
"${prefixDir}dev/umbum/my/package", | |
) | |
.map { it.removePrefix(prefixDir).replace("/", ".") } | |
.filter { it.contains("dto") } | |
println(packages.joinToString("\n")) | |
println("---") | |
packages | |
.flatMap { findAllClassesUsingClassLoader(it) } | |
.forEach { println(it) } | |
} | |
private fun findAllClassesUsingClassLoader(packageName: String): Set<Class<*>?> { | |
val stream = ClassLoader.getSystemClassLoader() | |
.getResourceAsStream(packageName.replace("[.]".toRegex(), "/")) ?: return emptySet() | |
val reader = BufferedReader(InputStreamReader(stream)) | |
return reader.lines() | |
.filter { it.endsWith(".class") } | |
.map { getClass(it, packageName) } | |
.collect(Collectors.toSet()) | |
} | |
private fun getClass(className: String, packageName: String): Class<*>? { | |
return Class.forName( | |
packageName + "." + className.substring(0, className.lastIndexOf('.')), | |
) | |
} | |
private fun getNestedDirectoryPaths(baseDirectoryPath: String): List<String> { | |
val nestedDirectoryPaths = mutableListOf<String>() | |
val queue: Queue<File> = ArrayDeque() | |
val baseDirectory = File(baseDirectoryPath) | |
if (baseDirectory.isDirectory) { | |
queue.add(baseDirectory) | |
} | |
while (queue.isNotEmpty()) { | |
val directory = queue.poll() | |
nestedDirectoryPaths.add(directory.absolutePath) | |
val files = directory.listFiles() | |
files?.forEach { | |
if (it.isDirectory) { | |
queue.add(it) | |
} | |
} | |
} | |
return nestedDirectoryPaths | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment