반응형
build.gradle.kts
implementation("org.jetbrains.kotlin:kotlin-compiler:1.8.21")
KotlinFileClassLoader
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import java.io.File
import java.net.URLClassLoader
import java.util.regex.Pattern
class KotlinFileClassLoader
fun main(args: Array<String>) {
val kotlinFiles = listOf(
File("/Users/demo-user/IdeaProjects/demo-project/src/main/kotlin/com/example/demo/DemoApplication.kt"),
File("/Users/demo-user/IdeaProjects/demo-project/src/main/kotlin/com/example/demo/model/Demo.kt")
)
val classes = compileKotlinFiles(kotlinFiles)
classes.forEach { println("${it.packageName}.${it.name}") }
}
fun compileKotlinFiles(kotlinFiles: List<File>): List<Class<*>> {
val outDir = File("out")
val arguments = K2JVMCompilerArguments().apply {
freeArgs = kotlinFiles.map { it.absolutePath }
classpath = System.getProperty("java.class.path")
destination = outDir.absolutePath
}
val collector = PrintingMessageCollector(System.err, MessageRenderer.PLAIN_RELATIVE_PATHS, arguments.verbose)
val compiler = K2JVMCompiler()
val exitCode = compiler.exec(collector, Services.EMPTY, arguments)
return URLClassLoader(arrayOf(outDir.toURI().toURL())).use { classLoader ->
kotlinFiles
.asSequence()
.map { it.absolutePath }
.map { Pattern.compile("src/main/kotlin/(.*)").matcher(it) }
.filter { it.find() }
.map { it.group(1) }
.map { it.replace("/", ".") }
.map { it.replace(".kt", "") }
.map { packageName: String -> classLoader.loadClass(packageName) }
.toList()
}
}
반응형
'Development > Kotlin' 카테고리의 다른 글
[Kotlin] Jackson (0) | 2024.12.31 |
---|---|
[Kotlin] Coroutine (0) | 2024.02.17 |
[Kotlin] 기본 문법 (0) | 2020.12.28 |